【typeHandler = JacksonTypeHandler.class掉坑记录】
typeHandler = JacksonTypeHandler.class掉坑记录
·
问题记录:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
影响代码:
List<Long> parkIds = user.getParkIds();
user表parkIds字段:
// 园区ids
@TableField(typeHandler = JacksonTypeHandler.class)
private List<Long> parkIds;
影响原因:
park_Ids在数据库数值为:[3,1540169179988041730,1541390598939951106,1,1541390598944145409]
由于“3”、“1”这两个过小的原因,此时@TableField(typeHandler = JacksonTypeHandler.class)注解自动封装这两个值为integer,即出现转换出错
解决方式:
①若使用该注解,尽量在入库时使用较长的id,例如雪花id
②使用自定义注解
@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中该字段存储的类型
@MappedTypes(List.class) // 需要转换的对象
public class ListInteger2ListLongTypeHandler extends BaseTypeHandler<List<Long>> {
private static ObjectMapper objectMapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
ps.setObject(i, JSON.toJSONString(parameter));
}
@Override
public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return getLongs(rs.getString(columnName));
}
@Override
public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return getLongs(rs.getString(columnIndex));
}
@Override
public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return getLongs(cs.getString(columnIndex));
}
private List<Long> getLongs(String value) {
if (StringUtils.hasText(value)) {
try {
CollectionType type = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class);
return objectMapper.readValue(value, type);
//List<Long> longs = JsonUtil.parseArray(value, Long.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return null;
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)