postgreSql存储jsonb

postgreSQL 支持 json类型存储
使用异同如下:

1. 字段修改

1.1 修改前

字符串类型

 private String files;
 -- 数据库
 files varchar(511),
1.2 修改后

jsonArray 类型

@TableField(typeHandler = JsonArrayTypeHandler.class)
 private JSONArray files;
 -- 数据库
 files jsonb,

2. 查询修改

2.1 修改前

使用mybatisPlus 默认查询

Map map = new HashMap(CommonConstant.TWO);
map.put(CommonConstant.FBR_INFO_ID, fbrInfoId);
List<FBRHWInfoEntity> hwList = fbrhwInfoMapper.selectByMap(map);
2.2 修改后

需要自己写查询的mapper方法

List<FBRHWInfoEntity> hwList = fbrhwInfoMapper.getByFbrInfoId(fbrInfoId); 

mapper中 resultMap 的其余字段不用写


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.npi.module.fbr.mapper.FBRHWInfoMapper">
    <resultMap id="CurrentType" type="com.xxx.npi.module.fbr.po.FBRHWInfoEntity">
        <result column="files" javaType="com.alibaba.fastjson.JSONObject" property="files"
                typeHandler="com.xxx.platform.common.mybatis.JsonArrayTypeHandler"/>
    resultMap>
    <select id="getByFbrInfoId" resultMap="CurrentType">
        select * from fbr_hw_info where fbr_info_id = #{param}
    select>
mapper>

3. 工具类

import com.alibaba.fastjson.JSONArray;
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;

/**
 * @description: JsonArrayTypeHandler
 * @author: leiming5
 * @date: 2021-02-07 08:57
 */
@MappedTypes({JSONArray.class})
public class JsonArrayTypeHandler extends BaseTypeHandler<Object> {

    private static final PGobject jsonObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("jsonb");
        jsonObject.setValue(o.toString());
        preparedStatement.setObject(i, jsonObject);
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return JSONArray.parseArray(resultSet.getString(columnName));
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return JSONArray.parseArray(resultSet.getString(columnIndex));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return JSONArray.parseArray(callableStatement.getString(columnIndex));
    }
}

你可能感兴趣的:(postgresql,数据库)