How to convert a list to a string in MyBatis?

In MyBatis, you can convert a List to a String using the following method:

  1. Utilize OGNL expressions: You can use OGNL expressions to concatenate the elements in a List into a string. For example:
<foreach collection="list" item="item" separator=",">
  ${item}
</foreach>

The list here is a parameter of type List, with item representing the elements within the list and separator being the delimiter used to connect the elements.

  1. By using a custom TypeHandler, you can customize a TypeHandler to handle parameters of type List. For example:
public class ListTypeHandler implements TypeHandler<List<String>> {

  @Override
  public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, StringUtils.join(parameter, ","));
  }

  @Override
  public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
    String value = rs.getString(columnName);
    return Arrays.asList(value.split(","));
  }

  @Override
  public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = rs.getString(columnIndex);
    return Arrays.asList(value.split(","));
  }

  @Override
  public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = cs.getString(columnIndex);
    return Arrays.asList(value.split(","));
  }
}

Next, use the @Param annotation in the methods of the Mapper interface to specify the TypeHandler for the parameters.

void updateList(@Param("list") List<String> list);

When used, the TypeHandler’s setParameter method will automatically convert a List into a String to be used as a parameter in SQL.

This way, you can convert a List into a String for use in MyBatis.

bannerAds