[json] springboot+mybatis+mysql+fastJson realizes the access of json objects in mysql

0. Prerequisites:

  • Requires mysql5.7.8 or above [now 5.7.20] to have the json object storage format
  • Require navicat to support json format
  • springboot inherits from mybatis

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

1. fastJson dependency

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

2. Rewrite a handler class

Inherit BaseTypeHandler, the generic type is JSONObject in fastJson,
refer to the following, you can directly copy and paste
this class and put it under com.xxx.xxx.handler, the handler package is at the same level as the controller package.
insert image description here

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. Specify the handler package path in the yaml file

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

4. The entity class in entity uses JSONObject type

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

5. Use typeHandler to specify the type in the mapper file

Focus on two points

  • If you use resultMap, you need to specify typeHandler
  • In the sql mapping in mapper, typeHanlder needs to be specified for each field of JSON type
<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. Test

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));

The result is shown in the figure:
insert image description here

7. Take json

mapper: ResultMap is written above, note that each field of type json must specify 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>

Get the json object, you can directly manipulate key-value pairs

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

Guess you like

Origin blog.csdn.net/NineWaited/article/details/128622424