MyBatis-Plus 插入数据库 JSON 字段完整方案(PostgreSQL / MySQL 两种主流)
一、两种数据库区分
- MySQL:字段类型
json / jsonb - PostgreSQL:字段类型
json / jsonb(你项目用PG)
核心:自定义类型处理器JacksonTypeHandler,自动 Java对象 ↔ 数据库JSON字符串
二、通用步骤(PG适用)
1. 数据库表字段示例
-- 附件扩展信息,存影像多波段、坐标、元数据杂项ALTERTABLEt_file_attachmentADDCOLUMNext_info JSONB;2. 实体类
importcom.baomidou.mybatisplus.annotation.TableField;importcom.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;importlombok.Data;importjava.time.LocalDateTime;importjava.util.Map;@DatapublicclassFileAttachment{privateLongid;privateStringoriginalFileName;privateStringfilePath;privateStringsensingTime;/** * 扩展JSON:波段信息、分辨率、四角坐标等 * typeHandler = JacksonTypeHandler.class 自动序列化/反序列化 */@TableField(typeHandler=JacksonTypeHandler.class)privateMap<String,Object>extInfo;// 也可以自定义实体接收JSON// @TableField(typeHandler = JacksonTypeHandler.class)// private TiffExtInfo extInfo;}3. 自定义JSON实体(可选,替代Map)
importlombok.Data;importjava.math.BigDecimal;@DatapublicclassTiffExtInfo{// 分辨率GSDprivateBigDecimalgsd;// 波段数量privateIntegerbandCount;// 影像宽高privateIntegerwidth;privateIntegerheight;// 四角坐标数组privatedouble[]bounds;}三、配置全局扫描TypeHandler(无需每个字段写注解)
application.yml
mybatis-plus:configuration:# 开启驼峰转下划线map-underscore-to-camel-case:truetype-handlers-package:com.xxx.xxx.handler四、插入使用示例
// 1. Map方式FileAttachmentattachment=newFileAttachment();attachment.setOriginalFileName("scene.tif");attachment.setSensingTime("2026-07-07T02:10:30Z");Map<String,Object>ext=newHashMap<>();ext.put("gsd",0.8);ext.put("bandCount",4);ext.put("width",10000);ext.put("height",8000);attachment.setExtInfo(ext);// MP直接插入,自动序列化为jsonb存入PGattachmentService.save(attachment);// 2. 自定义实体对象方式TiffExtInfotiffExt=newTiffExtInfo();tiffExt.setGsd(newBigDecimal("0.8"));tiffExt.setBandCount(3);tiffExt.setBounds(newdouble[]{116.3,39.9,116.5,40.1});attachment.setExtInfo(tiffExt);attachmentService.save(attachment);五、查询自动转对象
FileAttachmentfile=attachmentService.getById(1L);Map<String,Object>extMap=file.getExtInfo();// 或强转自定义实体// TiffExtInfo info = file.getExtInfo();六、常见坑(PG重点)
- 报错:无法转换类型 text to jsonb
- 实体必须加
@TableField(typeHandler = JacksonTypeHandler.class) - 或全局注册typeHandler包
- 实体必须加
- 更新JSON局部字段(MP Lambda)
Map<String,Object>newExt=newHashMap<>();newExt.put("gsd",1.0);attachmentService.lambdaUpdate().set(FileAttachment::getExtInfo,newExt).eq(FileAttachment::getId,1L).update();- JSONB条件查询(PG特有)
// 查询gsd=0.8的影像LambdaQueryWrapper<FileAttachment>wrapper=Wrappers.lambdaQuery();wrapper.apply("ext_info ->> 'gsd' = '0.8'");List<FileAttachment>list=attachmentService.list(wrapper);七、Maven依赖(必须有jackson)
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><!-- jackson序列化依赖,否则JacksonTypeHandler失效 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>