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
需要加一个转换方法:
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 类型
比如:
@TableField(typeHandler = PGJsonbTypeHandler.class) // 用于 PostgreSQL 的 JSONB 类型
private ShipToAddr shipToAddr;
原文地址:https://blog.csdn.net/puzi0315/article/details/143605751
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!