Mybatis-Plus 实现 jsonb类型的数据存取
1、自定义类型处理器
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.postgresql.util.PGobject; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JSONTypePgHandler<T extends Object> extends BaseTypeHandler<T> { private static final PGobject jsonObject = new PGobject(); private Class<T> clazz; public JSONTypePgHandler(Class<T> clazz) { if (clazz == null) throw new IllegalArgumentException("Type argument cannot be null"); this.clazz = clazz; } @Override public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { jsonObject.setType("json"); jsonObject.setValue(this.toJson(parameter)); ps.setObject(i, jsonObject); } @Override public T getNullableResult(ResultSet rs, String columnName) throws SQLException { return this.toObject(rs.getString(columnName), clazz); } @Override public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return this.toObject(rs.getString(columnIndex), clazz); } @Override public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return this.toObject(cs.getString(columnIndex), clazz); } private String toJson(T object) { try { return JSON.toJSONString(object, SerializerFeature.WriteNullListAsEmpty); } catch (Exception e) { throw new RuntimeException(e); } } private T toObject(String content, Class<?> clazz) { if (content != null && !content.isEmpty()) { try { return (T) JSON.parseObject(content,clazz); } catch (Exception e) { throw new RuntimeException(e); } } else { return null; } } }
2、存储:字段上添加处理器
@Schema(description = "当前处理人") @TableField(value = "current_handler", typeHandler = JSONTypePgHandler.class) private List<Handler> currentHandler;
3、读取:①、设置autoResultMap = true,自动为实体类生成一个结果映射;②、xml文件定义映射,数据库结果集中获取数据映射到Java对象的属性
@TableName(value = "tb_report_info",autoResultMap = true) public class ReportInfo {}
<resultMap id="ReportInfo" type="com.tdar.entity.ReportInfo"> <result property="currentHandler" column="current_handler" javaType="java.util.List" typeHandler="com.tdar.utils.JSONTypePgHandler"></result> </resultMap>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2018-05-28 java-网页404(个例)