Mybatis和Mysql的Json类型

Posted 骑着龙的羊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis和Mysql的Json类型相关的知识,希望对你有一定的参考价值。

mysql5.7新增加了Json类型字段,但是目前Mybatis中并不支持

1.新建MybatisJsonTypeHandler.java

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

//import org.apache.ibatis.type.BaseTypeHandler;
//import org.apache.ibatis.type.JdbcType;
//import org.codehaus.jackson.map.ObjectMapper;
//import org.codehaus.jackson.map.SerializationConfig.Feature;
//import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

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

/**
 * Author  : Randy
 * Date    : 2018-06-28  12:55
 * Comment :
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MybatisJsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private Class<T> clazz;

    public MybatisJsonTypeHandler(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(JsonParser.Feature.ALLOW_MISSING_VALUES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}

2.在mybatis-config.xml中注册该Handler

    <typeHandlers>
        <typeHandler handler="com.demo.handler.MybatisJsonTypeHandler"
                     javaType="com.demo.dto.ReportDataDto"/>
    </typeHandlers>

3.在mapper sql map中如下,其中content为mysql中的json类型字段

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.demo.mapper.ReportDataMapper" >

    <resultMap id="BaseResultMap" type="com.demo.dto.ReportDataDto" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <id column="content" property="content" jdbcType="VARCHAR" typeHandler="com.demo.common.MybatisJsonTypeHandler"/>
    </resultMap>

    <sql id="Base_Column_List" >
        id,
        create_time createTime,
        command_id commandId ,
        content,
        partition_key partitionKey
    </sql>

    <insert id="insert" parameterType="com.demo.dto.DataDto">
        insert into data(
            id,
            create_time,
            command_id,
            content,
            partition_key
        ) values (
              #{id},
              #{createTime},
              #{commandId},
              #{content,typeHandler=com.demo.common.MybatisJsonTypeHandler},
         #{partitionKey}
)
</insert>
</mapper>

  

  

  





以上是关于Mybatis和Mysql的Json类型的主要内容,如果未能解决你的问题,请参考以下文章

mybatis存取mysql中的json

使用 json rereiver php mysql 在片段中填充列表视图

Mybatis疑难事件簿:#‘传递布尔值无效问题

Mybatis深度整合Mysql的Json字段

SpringBoot+MyBatis Plus对Map中Date格式转换的处理

mybatis怎么修改字段为空