mysq5.7之后新增了json类型,但是在使用的过程中,Json数组中的值小于Integer.MAX_VALUE,则反序列化时会转成List类型,假设我们用的是List类型的话就会碰到类型转换错误的异常。
此方法可以返回对象的calss,自动转成对应的类型,但是在碰到List 类型的时候,由于calss只能获取到java.util.List类型无法获取List里对象的类型,就会导致会使用fastJson的默认转换类型,也就是当Json数组中的值小于Integer.MAX_VALUE,则反序列化时会转成List类型。所以当碰到这种情况时,可以使用以下方法。
@MappedJdbcTypes(value = JdbcType.VARCHAR) public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> { private static ObjectMapper mapper = new ObjectMapper(); private Class<T> clazz; public JsonTypeHandler(Class<T> clazz) { if (clazz == null) { throw new IllegalArgumentException("Type argument cannot be null"); } this.clazz = clazz; } @Override public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, this.toJson(parameter)); } @Override public T getNullableResult(ResultSet rs, String columnName) throws SQLException { return this.toObject(rs.getString(columnName), clazz); } @Override public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return this.toObject(rs.getString(columnIndex), clazz); } @Override public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return this.toObject(cs.getString(columnIndex), clazz); } private String toJson(T object) { try { return mapper.writeValueAsString(object); } catch (Exception e) { throw new RuntimeException(e); } } private T toObject(String content, Class<?> clazz) { if (content != null && !content.isEmpty()) { try { return (T) mapper.readValue(content, clazz); } catch (Exception e) { throw new RuntimeException(e); } } else { return null; } } }
指定返回值只能是 List
@MappedJdbcTypes(value = JdbcType.VARCHAR) @MappedTypes(List.class) public class JsonListLongTypeHandler extends BaseTypeHandler<List<Long>> { private static final ObjectMapper objectMapper = new ObjectMapper(); @Override public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, JSON.toJSONString(parameter)); } @Override public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException { return this.getLongs(rs.getString(columnName)); } @Override public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return this.getLongs(rs.getString(columnIndex)); } @Override public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return this.getLongs(cs.getString(columnIndex)); } private List<Long> getLongs(String value) { if (StringUtils.hasText(value)) { try { CollectionType type = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class); Object o1 = objectMapper.readValue(value, type); List<Long> o = objectMapper.readValue(value, type); return o; } catch (JsonProcessingException e) { e.printStackTrace(); } } return null; } }
以上是Java中的BaseTypeHandler自定义类型转换器如何使用的详细内容。更多信息请关注PHP中文网其他相关文章!