背景
springboot 2.2.6、postgresql12.3、mybatis-plus3.3.1tmp
页面有个功能需要存储的信息过于凌乱,不适合关系表存储,因此想使用json格式存储页面填写的信息。
设计表
CREATE TABLE "b_json" (
"id" varchar(64) COLLATE "pg_catalog"."default" NOT NULL,
"testjson" json,
CONSTRAINT "b_json_pkey" PRIMARY KEY ("id")
);
生成代码
使用sf-generator生成代码
修改entity
必须给注解@TableName添加上autoResultMap = true
如:@TableName(value = “b_json”, autoResultMap = true)
package com.***.entity;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.***.BaseEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
@Data
@TableName(value = "b_json", autoResultMap = true)
@ToString(callSuper = true)
public class BJsonEntity extends BaseEntity {
@ApiModelProperty(value = "测试")
@TableField(value = "testjson", typeHandler = JacksonTypeHandler.class)
private JSONObject testjson;
}
处理mapper
需要使用resultMap,至少需要指定json字段的信息:jdbcType、javaType、typeHandler。插入的时候可以直接使用mybatis-plus的内置方法,查询的时候需要使用resultMap。
<?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.***.mapper.BJsonMapper">
<resultMap id="BaseResultMap" type="com.***.entity.BJsonEntity">
<id column="id" jdbcType="VARCHAR" property="id"/>
<result column="testjson" jdbcType="OTHER" property="testjson" javaType="com.alibaba.fastjson.JSONObject"
typeHandler="com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler"/>
</resultMap>
<insert id="add" parameterType="com.***.entity.BJsonEntity">
INSERT INTO b_json(
id
<if test="vo.testjson!= null ">
testjson,
</if>
create_time)
VALUES (
#{vo.id,jdbcType=VARCHAR},
<if test="vo.testjson!= null ">
#{vo.testjson,jdbcType=OTHER, javaType=com.alibaba.fastjson.JSONObject ,typeHandler=com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler},
</if>
now()
);
</insert>
<select id="queryList" resultMap="BaseResultMap" resultType="java.util.HashMap">
select * from b_json b
where 1=1
<if test="ent.id != null and ent.id != ''">and b.id = #{ent.id}
</if>
</select>
</mapper>
配置数据库连接
需要在数据库连接追加&stringtype=unspecified,否则插入数据的时候报错
ERROR: column “testjson” is of type json but expression is of type character varying