【json】springboot+mybatis+mysql+fastJson实现json对象在mysql中的存取

0.前提要求:

  • 要求mysql5.7.8以上【现5.7.20】才有json对象存储格式
  • 要求navicat支持json格式
  • springboot继承mybatis

参考:
https://blog.csdn.net/qq_34382367/article/details/88890260 https://www.cnblogs.com/ceshi2016/p/7381478.html

1.fastJson依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.11</version>
</dependency>

2.重写一个handler类

继承BaseTypeHandler,泛型为fastJson中的JSONObject
参考如下,可直接复制粘贴
该类放到com.xxx.xxx.handler下即可,handler包与controller包同级。
在这里插入图片描述

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @Project
 * @Autor
 * @Create 2019/7/16 1:32 PM
 * @Description
 */
@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;
    }
}

3.在yaml文件中指定handler包路径

mybatis:
  # 指定实体类
  type-aliases-package: com.emergency.templatemanager.entity
  # 指定mapper映射配置包
  mapper-locations: classpath:mybatis/mapper/*.xml
  # 指定handler的位置
  type-handlers-package: com.emergency.templatemanager.handler

4.entity中实体类使用JSONObject类型

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class TemplateContent {
    
    
    Integer tid;
    JSONObject directoryStructure;
    JSONObject specialHeadquartersData;
    JSONObject fieldHeadquartersData;
    JSONObject earlyWarningResponseData;
    JSONObject emergencyResponseData;
}

5.mapper文件中使用typeHandler指定类型

关注两个点

  • 使用resultMap的话要指定typeHandler
  • mapper中的sql映射中对于每个JSON类型的字段都需要指定typeHanlder
<resultMap type="com.emergency.templatemanager.entity.TemplateContent" id="TemplateContentResultMap">
    <!-- 用result属性来映射非主键字段 -->
    <result property="tid" column="tid"/>
    <result property="directoryStructure" column="directory_structure"/>
    <result property="specialHeadquartersData" column="special_headquarters_data" typeHandler="com.emergency.templatemanager.handler.MySqlJsonHandler"/>
    <result property="fieldHeadquartersData" column="field_headquarters_data" typeHandler="com.emergency.templatemanager.handler.MySqlJsonHandler"/>
    <result property="earlyWarningResponseData" column="early_warning_response_data" typeHandler="com.emergency.templatemanager.handler.MySqlJsonHandler"/>
    <result property="emergencyResponseData" column="emergency_response_data" typeHandler="com.emergency.templatemanager.handler.MySqlJsonHandler"/>
</resultMap>
<insert id="newTemplateContent" parameterType="com.emergency.templatemanager.entity.TemplateContent">
    insert into templateContent
    (tid,directory_structure,special_headquarters_data,field_headquarters_data,early_warning_response_data,emergency_response_data)
    values(#{templateContent.tid},
    #{templateContent.directoryStructure, typeHandler=com.emergency.templatemanager.handler.MySqlJsonHandler},
    #{templateContent.specialHeadquartersData, typeHandler=com.emergency.templatemanager.handler.MySqlJsonHandler},
    #{templateContent.fieldHeadquartersData, typeHandler=com.emergency.templatemanager.handler.MySqlJsonHandler},
    #{templateContent.earlyWarningResponseData, typeHandler=com.emergency.templatemanager.handler.MySqlJsonHandler},
    #{templateContent.emergencyResponseData, typeHandler=com.emergency.templatemanager.handler.MySqlJsonHandler})
</insert>

6.测试

Map map = new HashMap();
map.put("1", 123);
map.put("2", "222");
map.put("3", new HashMap());
JSONObject object = JSONObject.parseObject(JSON.toJSONString(map));
templateDao.newTemplateContent(new TemplateContent(1, object,object,object,object,object));

结果如图:
在这里插入图片描述

7.取json

mapper:ResultMap上面有写到,注意每个json类型的字段都要指定typeHandler

<select id="getTemplatesContent" resultMap="TemplateContentResultMap">
    select tid,directory_structure,special_headquarters_data,field_headquarters_data,early_warning_response_data,emergency_response_data
    from templateContent
</select>

获取json对象,可直接操作键值对

List<TemplateContent> list = templateDao.getTemplatesContent();
list.stream().forEach((e) -> {
    
    
    JSONObject json = e.getDirectoryStructure();
    System.out.println(json.get("1"));
});

猜你喜欢

转载自blog.csdn.net/NineWaited/article/details/128622424