springboot集成mybatis处理json类型

springboot集成mybatis处理json类型数据

今天做了一个需求,需要将一个字段定义为json类型,加以记录

  1. 使用的mysql数据库,在数据库中新建一个表,parameter字段为json类型
CREATE TABLE `sms_template` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `template_name` varchar(30) NOT NULL COMMENT '模板名称',
  `template_code` varchar(20) DEFAULT NULL COMMENT '模板编号',
  `sign_name` varchar(16) DEFAULT NULL COMMENT '短信签名',
  `template_content` varchar(100) DEFAULT NULL COMMENT '短信模板内容',
  `parameter` json DEFAULT NULL COMMENT '变量参数',
  `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标识  0:未删除 1:删除',
  `operator_code` varchar(11) DEFAULT NULL,
  `operator_name` varchar(10) NOT NULL COMMENT '创建人名称',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='短信模板表';
  1. mybatis处理json配置类
@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MySqlJsonHandler extends BaseTypeHandler<JSONObject> {
    /**
     * 设置非空参数
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i,String.valueOf(parameter.toJSONString()));
    }
    /**
     * 根据列名,获取可以为空的结果
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlJson = rs.getString(columnName);
        if (null != sqlJson) {
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }
    /**
     * 根据列索引,获取可以为内控的接口
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlJson = rs.getString(columnIndex);
        if (null != sqlJson) {
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }
    /**
     *
     * @param cs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlJson = cs.getNString(columnIndex);
        if (null != sqlJson) {
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }
}
  1. 在xml文件中注明typeHandler
<resultMap id="BaseResultMap" type="cn.net.yzl.sms.model.entity.SmsTemplate">
        <!--@Table sms_template-->
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="templateName" column="template_name" jdbcType="VARCHAR"/>
        <result property="templateCode" column="template_code" jdbcType="VARCHAR"/>
        <result property="templateContent" column="template_content" jdbcType="VARCHAR"/>
        <result property="parameter" column="parameter" typeHandler="cn.net.yzl.sms.config.mybatis.MySqlJsonHandler"/>
        <result property="operatorCode" column="operator_code" jdbcType="VARCHAR"/>
        <result property="operatorName" column="operator_name" jdbcType="VARCHAR"/>
        <result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
    </resultMap>
  1. 新增语句
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into sms_template
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="templateName != null and '' != templateName">
                template_name,
            </if>
            <if test="templateCode != null and '' != templateCode">
                template_code,
            </if>
            <if test="templateContent != null and '' != templateContent">
                template_content,
            </if>
            <if test="parameter != null">
                parameter,
            </if>
            <if test="operatorCode != null and '' != operatorCode">
                operator_code,
            </if>
            <if test="operatorName != null and '' != operatorName">
                operator_name,
            </if>
            <if test="updateTime != null">
                update_time,
            </if>
            <if test="createTime != null">
                create_time
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="templateName != null and '' != templateName">
                #{templateName},
            </if>
            <if test="templateCode != null and '' != templateCode">
                #{templateCode},
            </if>
            <if test="templateContent != null and '' != templateContent">
                #{templateContent},
            </if>
            <if test="parameter != null">
                #{parameter,typeHandler=cn.net.yzl.sms.config.mybatis.MySqlJsonHandler},
            </if>
            <if test="operatorCode != null and '' != operatorCode">
                #{operatorCode},
            </if>
            <if test="operatorName != null and '' != operatorName">
                #{operatorName},
            </if>
            <if test="updateTime != null">
                #{updateTime},
            </if>
            <if test="createTime != null">
                #{createTime}
            </if>
        </trim>
    </insert>

在新增的字段上加上typeHandler即可
5. 查询语句

<select id="queryByName" parameterType="com.ttao.sms.vo.SmsTemplateQueryVO"
            resultMap="BaseResultMap" resultType="com.ttao.sms.dto.SmsTemplateDTO">
        select
        <include refid="Base_Column_List"/>
        from sms_template
        where template_name = #{tempName}
        and del_flag = 0
    </select>

查询时加上先前定义好的resultMap