需求
利用[mybatis-plus 3.4.1]在做插入/更新之前将对象内复杂类型字段自动转换成json串,查询要用的时候再自动的从json转换成对象
问题描述
数据表中字段类型为longText的字段,实体类中类型也同样设置为JAVA对象,但MyBatis-Plus查询数据时为null,其余数据都可正常查询出来。
解决方案
利用@TableField 和自定义类型转换器
自定义转换器
@MappedTypes({DataContent.class})
@MappedJdbcTypes(value = JdbcType.VARCHAR)
public class DataContentToString extends AbstractJsonTypeHandler<DataContent> {
@Override
protected DataContent parse(String json) {
if (Strings.isNullOrEmpty(json)) {
return new DataContent();
}
try {
return OBJECT_MAPPER.readValue(json, DataContent.class);
} catch (JsonProcessingException e) {
throw new RuntimeException("类型转换失败", e);
}
}
@Override
protected String toJson(DataContent obj) {
if (obj == null) {
return "{}";
}
try {
return OBJECT_MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("类型转换失败", e);
}
}
}
实体类
@Data
@TableName(autoResultMap = true)
public class Entity {
private String id;
## 此处填写自定义转换器
@TableField(typeHandler = DataContent.class)
private DataJobContent process;
}
踩过的坑
1、网上的解决方法都不合适。要不就很复杂,要不就是要改ResultMap、要不就是建议selectByExampleWithBLOBs,但3.4.1不存在!!耽误很久!!
2、自定义完类型转换器后,插入能够正常插入,查询依旧为空,断点到父类发现 查询时不走类型转换器,百度出的自定义的类型转换器的写法都对,查阅官网后,发现忽略了在实体类上填加 autoResultMap = true