Mybatis中如何映射mysql中的JSON字段
数据库mysql中的的某一个字段,存放的是一个List <String>的集合,需要将字段对应到entity的某一个参数上,mapper.xml中使用<id property="abnormalEigenList" column="AbnormalEigen">的方式直接进行字段映射时,会出现java.lang.IllegalStateException: No typehandler found for property abnormalEigenList,具体的错误:
java.lang.IllegalStateException: No typehandler found for property abnormalEigenList at org.apache.ibatis.mapping.ResultMapping$Builder.validate(ResultMapping.java:151) at org.apache.ibatis.mapping.ResultMapping$Builder.build(ResultMapping.java:140) at org.apache.ibatis.builder.MapperBuilderAssistant.buildResultMapping(MapperBuilderAssistant.java:446) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildResultMappingFromContext(XMLMapperBuilder.java:393) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:280) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:254) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElements(XMLMapperBuilder.java:246) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:119)
这时,我们需要定义一个类,对该json字符串进行转义:
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import java.util.ArrayList;
import java.util.List;
/**
* @author:
* @date: 2023-07-02 15:08
* @description: 进行json字段的转换
*/
public class JsonHandler extends JacksonTypeHandler {
public JsonHandler (Class<?> type) {
super(type);
}
@Override
protected List<String> parse(String json) {
List<String> jsons = new ArrayList<>();
try {
jsons = JSONObject.parseArray(json, String.class);
} catch (JSONException e) {
jsons.add(JSONObject.parseObject(json, String.class));
}
return jsons;
}
}在mapper.xml中,需要在字段映射时加入typeHandler,具体:<id property="abnormalEigenList" column="AbnormalEigen" typeHandler="com.xxx.config.JsonHandler">
到此这篇关于Mybatis中映射mysql中的JSON字段的文章就介绍到这了,更多相关mysql JSON字段内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java8中stream流的collectingAndThen方法应用实例详解
Java8中的Stream流提供了collectingAndThen方法,用于对归纳结果进行二次处理,文章通过User类的数据填充,演示了如何使用该方法进行集合去重、查找最高工资员工、计算平均工资等操作,感兴趣的朋友跟随小编一起看看吧2025-03-03
idea自带Jacoco/idea自动测试语句覆盖率方法(使用详解)
这篇文章主要介绍了idea自带Jacoco/idea自动测试语句覆盖率方法,本文给大家分享使用方法,通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-04-04


最新评论