SpringBoot集成MyBatis操作MySql8的JSON类型

SpringBoot集成MyBatis操作MySql8的JSON类型

1.定义Json类型转换器:JsonTypeHandler

  • 一个包有一个类型转换器就够了
  • 开箱即用,复制即可
java 复制代码
package com.ins.iot.sync.server.handle;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {
    private static final ObjectMapper mapper = new ObjectMapper();
    private Class<T> clazz;

    public JsonTypeHandler(Class<T> clazz) {
        if (clazz == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName), clazz);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex), clazz);
    }

    private String toJson(T object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class<?> clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return (T) mapper.readValue(content, clazz);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

    static {
        //mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}

2.使用Json类型转换器:JsonTypeHandler

  • entity: 使用JSONObject类型
java 复制代码
@Data
@NoArgsConstructor
public class Org {
 
    private Long orgId

    @ApiModelProperty(value = "参数信息")
    private JSONObject paramInfo;
 }
  • mapper
  1. JSONObject 保存到MySql数据库的 json字段
  2. 数据库的 json字段 取出并转化成 JSONObject
java 复制代码
   <mapper namespace="com.xxx.xxx.xxx.mapper.OrgMapper">

      <insert id="insertBatch" parameterType="java.util.List">
        insert into org (orgid,,paraminfo)
        values
        <foreach collection="list" item="org" separator=",">
            (
            #{org.orgId},#{org.paramInfo, typeHandler=com.xxx.xx.xxx.handle.JsonTypeHandler}
            )
          </foreach>
      </insert>


       <resultMap id="orgResult" type="com.xxx.xxx.xxx.Org">
             <result property="orgId" column="orgid"/>
            <result property="paramInfo" column="paraminfo" javaType="com.alibaba.fastjson.JSONObject" typeHandler="com.ins.iot.sync.server.handle.JsonTypeHandler"/>
        </resultMap>
       
       <select id="srg" resultMap="orgResult">
        select
              orgid,paraminfo
        from org
    </select>
相关推荐
余槐i4 分钟前
开虚拟线程后接口反而更慢:JDK 21 synchronized 锁住载体线程的排查
java·spring boot·redis·mysql·性能优化
RuoyiOffice39 分钟前
Flowable 状态通知设计:单体用本地事件,微服务如何回写业务状态?
spring boot·微服务·vue3·flowable·ruoyi office·redis stream·流程状态通知
ly76891 小时前
Spring Security 过滤器链定制:认证、CORS 与 CSRF 的先后顺序
java·spring boot·spring·spring security·csrf·cors·过滤器链
bksczm17 小时前
Redis数据结构之string
java·redis·mybatis
紧跟先前的步伐19 小时前
Go AI Agent 实战 11|请求结构、响应结构与 JSON 解析
人工智能·ai·golang·json
9527!到!19 小时前
Springboot @value读取配置参数踩坑&推荐解决方案
java·spring boot·spring
十年Java程序媛19 小时前
Java 面试常问 this、super:构造方法调用顺序避坑
java·开发语言·spring boot·面试·个人开发
小蒜学长1 天前
基于SpingBoot+Vue的定向越野赛事管理系统的设计与开发(代码+数据库+LW)
java·前端·spring boot·后端·前后端分离·定向越野赛事
RuoyiOffice1 天前
项目预算和交付日期变了,为什么不能直接改台账?
spring boot·项目管理·vue3·flowable·业务建模·ruoyi office·项目变更
小蒜学长1 天前
基于过程性评价的ai助学平台(代码+数据库+LW)
java·spring boot·后端·微信小程序·过程性评价