Mybatis中如何映射mysql中的JSON字段
作者:蓝色格子
在mapper.xml中,需要在字段映射时加入typeHandler,具体:<id property="abnormalEigenList" column="AbnormalEigen" typeHandler="com.xxx.config.JsonHandler">,下面通过本文给大家介绍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字段内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
