Technology Sharing

[PostgreSQL] Spring boot Mybatis-plus PostgreSQL handles json type

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

I. Introduction

In the development of Springboot projects, relational databases are generally used as the main database to store data. Sometimes business scenarios require the expansion of custom business information on the existing table structure. In this scenario, json type storage is generally used. This article summarizes the practical solution of operating json with Mybatis-plus in Springboot projects.

2. Technology Stack

Spring boot + Mybatis-plus + PostgreSQL, a field in the PostgreSQL database is of json type.

insert image description here

3. Background Analysis

In MyBatis, TypeHandler plays the role of a bridge between JavaType and JdbcType. They are used to set the value of a Java object to PreparedStatement or to retrieve values ​​from ResultSet or CallableStatement when executing SQL statements.

MyBatis-Plus provides some built-in type processors that can be used TableField Annotations are quickly injected into the MyBatis container, simplifying the development process. MyBatis-Plus field type processor official reference documentation:Field Type Processor | MyBatis-Plus (baomidou.com)

JSON Field Type Handler

MyBatis-Plus has built-in multiple JSON type processors, including AbstractJsonTypeHandler and its subclassesFastjson2TypeHandlerFastjsonTypeHandlerGsonTypeHandlerJacksonTypeHandler Etc. These processors can convert JSON strings to and from Java objects.

4. Solution Analysis

4.1 Storing JSON objects directly in the PostgreSQL database

The PostgreSQL database fields are shown above: param_config is a json type field.

Step 1: DO entity writing

The field data type is com.alibaba.fastjson2.JSONObject

@Data
@Accessors(chain = true)
@TableName(autoResultMap = true)
public class User {
    
    private Long id;

    ...

    /**
   	 * 关键代码!!!
     * 必须开启映射注解
     *
     * @TableName(autoResultMap = true)
     *
     * 选择对应的 JSON 处理器,并确保存在对应的 JSON 解析依赖包
     */
    @TableField(value = "param_config", typeHandler = JacksonTypeHandler.class)
    // 或者使用 FastjsonTypeHandler
    // @TableField(typeHandler = FastjsonTypeHandler.class)
    private JSONObject paramConfig;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Step 2: XML configuration corresponding writing method

<!-- 关键代码!!!!!!! -->
<!-- 单个字段的类型处理器配置 -->
<result column="param_config" jdbcType="VARCHAR" property="paramConfig" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler" />

<!-- 多个字段中某个字段的类型处理器配置 -->
<resultMap id="departmentResultMap" type="com.baomidou...DepartmentVO">
    <result property="director" column="director" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler" />
</resultMap>
<select id="selectPageVO" resultMap="departmentResultMap">
   select id,name,director from department ...
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

View the results saved in the database, as shown below:

insert image description here

4.2 Storing json strings in PostgreSQL database

First add the following to the PostgreSQL database URL: &stringtype=unspecifiedNote that if the database name is directly before this configuration, you need to & Replace?

Step 1: DO entity class writing

@TableField(value = "param_config", typeHandler = JacksonTypeHandler.class)
private String paramConfig;
  • 1
  • 2

Step 2: XML configuration corresponding writing method

<!-- 单个字段的类型处理器配置 -->
<result column="param_config" jdbcType="VARCHAR" property="paramConfig" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler" />
  • 1
  • 2

View the results saved in the database, as shown below:

insert image description here

5. Custom type processor

In MyBatis-Plus, in addition to using built-in type processors, developers can also customize type processors as needed.

For example, when using the PostgreSQL database, you may encounter fields of type JSON. In this case, you can create a custom type handler to handle JSON data.

5.1 Defining Type Handlers

The following is an example of a custom JSON type handler:

package com.ruoyi.common.utils.pg;

import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

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

/**
 * @ClassName: JsonTypeHandlerPg
 * @Description: json对象处理
 * @Author: hjm
 * @Date: 2024-07-11 10:34
 */
@MappedTypes(String.class)
public class JsonTypeHandlerPg extends BaseTypeHandler<String> {

    /**
     * 引入PGSQL提供的工具类PGobject
     */
    private static final PGobject JSON_OBJECT = new PGobject();
    public static final String JSON_TYPE = "json";

    /**
     * 关键位置!!!
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String param, JdbcType jdbcType) throws SQLException {
        JSON_OBJECT.setType(JSON_TYPE);
        JSON_OBJECT.setValue(param);
        ps.setObject(i, JSON_OBJECT);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlJson = rs.getString(columnName);
        if (StringUtils.isNotBlank(sqlJson)) {
            return sqlJson;
        }
        return null;
    }

    // 根据列索引,获取可以为空的结果
    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlJson = rs.getString(columnIndex);
        if (StringUtils.isNotBlank(sqlJson)) {
            return sqlJson;
        }
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlJson = cs.getString(columnIndex);
        if (StringUtils.isNotBlank(sqlJson)) {
            return sqlJson;
        }
        return null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

5.2 Using custom type handlers

In the entity class, through TableField Annotation specifies a custom type processor:

/**
 * 测试对象
 *
 * @author hjm
 * @date 2024-07-11
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("data_test")
public class DataTest extends BaseEntity {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id")
    private Long id;
    
    /**
     * 关键位置!!!
     */
    @TableField(typeHandler = JsonTypeHandlerPg.class)
    private String jsonData;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

Modify the mapper file

<?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.ruoyi.dt.mapper.DataTestMapper">

    <resultMap type="com.ruoyi.dt.domain.DataTest" id="DataTestResult">
        <result property="id" column="id"/>
		<!-- 关键位置!!! -->
        <result property="jsonData" column="json_data" typeHandler="com.ruoyi.common.utils.pg.JsonTypeHandlerPg"/>
        <result property="createBy" column="create_by"/>
        <result property="createTime" column="create_time"/>
        <result property="updateBy" column="update_by"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>

</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Business code

    /**
     * 新增数据
     */
    @Override
    public Boolean insertByAo(DataTestAo ao) {
        DataTest add = BeanUtil.toBean(ao, DataTest.class);
        // 关键位置!!!
		add.setJsonData(JSONUtil.toJsonStr(ao));
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            ao.setId(add.getId());
        }
        return flag;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

This article is finished!