举例:
逗号分隔字符串列表存储数据库,格式为:xxx,xxx,xxx,以下是自定义类型处理器:
/**
* @desc List<String> 的类型转换器实现类
*/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class StringListTypeHandler implements TypeHandler<List<String>> {
private static final String COMMA = ",";
@Override
public void setParameter(PreparedStatement ps, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
// 设置占位符
ps.setString(i, CollUtil.join(strings, COMMA));
}
@Override
public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
return getResult(value);
}
@Override
public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
String value = rs.getString(columnIndex);
return getResult(value);
}
@Override
public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = cs.getString(columnIndex);
return getResult(value);
}
private List<String> getResult(String value) {
if (value == null) {
return null;
}
return StrUtil.splitTrim(value, COMMA);
}
}
问题一:
查询/删除报错:argument type mismatch
解决办法:在实体类上加:
@NoArgsConstructor
@AllArgsConstructor
问题二:
查询结果注解的字段一直为 null,实际数据库字段有值,例:
@TableField(typeHandler = StringListTypeHandler.class) private List<String> fileUrls;
解决办法:
application.yaml 的 mybatis-plus 节点加上配置:type-handlers-package,例:
# MyBatis Plus 的配置项
mybatis-plus:
type-handlers-package: 自定义类型处理器包路径,例:com.xxx.xxx
文章评论