mybatis连接PGSQL中对于json和jsonb的处理

pgsql数据库表字段设置了jsonb格式;在java的实体里使用String或者对象转换会一直提示一个错误:

Caused by: org.postgresql.util.PSQLException: ERROR: column "xx" is of type jsonb but expression is of type character varying

需要加一个转换方法:

java 复制代码
import com.alibaba.fastjson.JSON;
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;

/**
 *  PGJsonTypeHandler:处理Object对象类型与postgresql中JSONB类型之间的转换
 *  author:lipu
 *  created_at:2021/07/29 14:00
 */
@SuppressWarnings("unchecked")
@MappedTypes(value = {Object.class})
public class PGJsonbTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private static final PGobject pgObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T parameter, JdbcType jdbcType) throws SQLException {
        if (preparedStatement != null) {
            pgObject.setType("jsonb");
            pgObject.setValue(JSON.toJSONString(parameter));
            preparedStatement.setObject(i, pgObject);
        }
    }


    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (T) JSON.parse(rs.getString(columnName));
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (T) JSON.parse(rs.getString(columnIndex));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (T) JSON.parse(cs.getString(columnIndex));
    }
}

定义实体DO的时候,指定:

复制代码
@TableField(typeHandler = PGJsonbTypeHandler.class) // 用于 PostgreSQL 的 JSONB 类型

比如:

java 复制代码
    @TableField(typeHandler = PGJsonbTypeHandler.class) // 用于 PostgreSQL 的 JSONB 类型
    private ShipToAddr shipToAddr;
相关推荐
用户298698530142 小时前
在 Python 中把 Word 文档转换为 JSON 的三种实现方式
python·json·api
未秃头的程序猿2 小时前
给新模块加了个 @MapperScan,启动崩了,最后发现跟 MapperScan 没关系
java·后端·mybatis
FRing032 天前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
用户298698530142 天前
使用 Python 将 JSON 转换为 Word 文档的实践指南
python·json·api
九英里路3 天前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
wuyk5553 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk5554 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
阿达和自己4 天前
springboot学习-springboot引入MyBatis-Plus
spring boot·学习·mybatis
2603_969694855 天前
【JavaWeb学习记录】MyBatis核心知识点与实战笔记:从入门到动态SQL
笔记·sql·学习·mysql·mybatis·javaweb·学习方法
wang_shu_mo_ran5 天前
MyBatis 从入门到进阶(一)
java·spring·mybatis