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();@Overridepublic 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);}}@Overridepublic T getNullableResult(ResultSet rs, String columnName) throws SQLException {return (T) JSON.parse(rs.getString(columnName));}@Overridepublic T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return (T) JSON.parse(rs.getString(columnIndex));}@Overridepublic 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;