在使用mybatis-plus自带的json转换实体的时候自动转换成LinkHashMap然而直接使用会报强转异常,自己写了一个
首先是
BaseAttributeTypeHandler工具类 public class BaseAttributeTypeHandler<T> extends BaseTypeHandler<Object> { private JavaType javaType; /** * ObjectMapper */ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); /** * 构造方法 */ public JsonArrayTypeHandler() { ResolvableType resolvableType = ResolvableType.forClass(getClass()); Type type = resolvableType.as(JsonArrayTypeHandler.class).getGeneric().getType(); javaType = constructType(type); } public static JavaType constructType(Type type) { Assert.notNull(type, "[Assertion failed] - type is required; it must not be null"); return TypeFactory.defaultInstance().constructType(type); } @Override public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, JSONUtil.toJsonStr(parameter)); } @Override public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { String value = rs.getString(columnName); return convertToEntityAttribute(value); } @Override public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return convertToEntityAttribute(rs.getString(columnIndex)); } @Override public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String value = cs.getString(columnIndex); return convertToEntityAttribute(value); } public Object convertToEntityAttribute(String dbData) { if (StringUtils.isEmpty(dbData)) { if (List.class.isAssignableFrom(javaType.getRawClass())) { return Collections.emptyList(); } else if (Set.class.isAssignableFrom(javaType.getRawClass())) { return Collections.emptySet(); } else if (Map.class.isAssignableFrom(javaType.getRawClass())) { return Collections.emptyMap(); } else { return null; } } return toObject(dbData, javaType); } public static <T> T toObject(String json, JavaType javaType) { Assert.hasText(json, "[Assertion failed] - this json must have text; it must not be null, empty, or blank"); Assert.notNull(javaType, "[Assertion failed] - javaType is required; it must not be null"); try { return OBJECT_MAPPER.readValue(json, javaType); } catch (com.fasterxml.jackson.core.JsonParseException e) { throw new RuntimeException(e.getMessage(), e); } catch (JsonMappingException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } }然后在typehandler使用哪种类型就重建一个类去集成这个类,我需要转换一个List<SpecificationValue>这个结构的list嵌套对象的结构
public class SpecificationTypeHandler extends BaseAttributeTypeHandler<List<SpecificationValue>> { }然后在typehandler中添加
@TableField( typeHandler = SpecificationTypeHandler.class) private List<SpecificationValue> specificationValues;搞定
