mybatis连接PGSQL中对于json和jsonb的处理
TableField(typeHandler = PGJsonbTypeHandler.class) // 用于 PostgreSQL 的 JSONB 类型。pgsql数据库表字段设置了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 类型
比如:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@TableName(value = "tb1",autoResultMap = true)
@KeySequence("tb1_id_seq")
@Schema(description = "基本表")
public class Table1DO {
@TableId
@Schema(description = "主键")
private Long id;
@TableField(typeHandler = PGJsonbTypeHandler.class) // 用于 PostgreSQL 的 JSONB 类型
private ShipToAddr shipToAddr;
@Schema(description = "产品图片地址列表") // 用于 PostgreSQL 的 JSONB 类型
@TableField(typeHandler = PGJsonbTypeHandler.class)
private List<String> productImages;
}
注意:类上的 @TableName里一定要加上autoResultMap = true
@TableName(value = "tb1",autoResultMap = true)

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)