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>
相关推荐
vipxieliang23 分钟前
ValidX错误消息国际化完全指南:8种语言9个语言包与三级回退机制
java·spring boot
钱栈up2 小时前
别忽略INFO日志:我用AI编码助手1小时修完3个接口的隐藏Bug
后端·json·trae
MetaLite2 小时前
SpringBoot接口通用返回对象Resp设计
java·spring boot·后端
小江的记录本3 小时前
【ORM 框架】MyBatis-Plus 核心特性、条件构造器、分页插件、乐观锁插件(附《思维导图》、《问题排查与实践清单》和《面试高频考点汇总》)
java·windows·spring boot·python·spring·面试·mybatis
小江的记录本3 小时前
【ORM框架】MyBatis核心原理、ORM思想、MyBatis vs JPA
java·数据库·后端·spring·spring cloud·oracle·mybatis
迷迭香yy4 小时前
A股数据本地存储方案对比JSON、SQLite、ClickHouse、DuckDB怎么选 IG50免费开源股票数据API接口
clickhouse·sqlite·json
MetaLite4 小时前
SpringBoot整合Caffeine-集群本地缓存如何保证分布式一致性
spring boot·分布式·缓存
黑马程序员毕设4 小时前
基于B/S架构的“指尖乡味”助农电商小程序系统设计与实现
spring boot·微信小程序·小程序·架构·课程设计·毕设
卓怡学长15 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea