第一种:使用MySQL数据库的JSON数据类型映射对象
在使用对象作为JSON字段的映射时,在实体类上要加上autoResultMap的配置,否则会导致在反序列化时,对象不能够正确映射到实体类;
@TableName(value = "talble_name", autoResultMap = true)
public class Entity {
@TableField(value = "table_file", typeHandler = JacksonTypeHandler.class)
private JsonObject tableFile;
}
第二种:使用MySQL数据库的JSON数据类型映射数组
我的解决方式可能不是最优雅的,但有效,暂时没太多时间去研究最优雅的解决方式,因为我感觉这里的泛型,应该可以通过@MappedTypes注解配置或者指定局部变量specificType也使用泛型的方式(实测不行,应该会产生泛型擦除,不能够正确地转换)更加优雅地实现,记录一下我现在的做法;
1.首先先配置一个基类,指定数组类型的反序列化基础;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@MappedJdbcTypes(JdbcType.VARBINARY)
@MappedTypes({List.class})
public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
String content = CollUtil.isEmpty(parameter) ? null : JSON.toJSONString(parameter);
ps.setString(i, content);
}
@Override
public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return this.getListByJsonArrayString(rs.getString(columnName));
}
@Override
public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(rs.getString(columnIndex));
}
@Override
public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(cs.getString(columnIndex));
}
private List<T> getListByJsonArrayString(String content) {
return StrUtil.isBlank(content) ? null : JSON.parseObject(content, this.specificType());
}
/**
* 具体类型,由子类提供
*
* @return 具体类型
*/
protected abstract TypeReference<List<T>> specificType();
}
第二步:在使用到具体数据类型Entity的地方,重写该Entity的反序列化配置类
public class EntityListTypeHandler extends ListTypeHandler<Entity> {
@Override
protected TypeReference<List<Entity>> specificType() {
return new TypeReference<>() {
};
}
}
第三步: 增加autoResultMap 配置,且在对应的属性配置反序列化类
@TableName(value = "table_name", autoResultMap = true)
@TableField(value = "table_filed", typeHandler = EntityListTypeHandler.class)
private List<Entity> tableFiled;