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中文網其他相關文章!