Mybatis-Plus 对 json 的存储使用支持
Mybatis-Plus 对 json 的存储使用支持
场景分析:
随着数据库对字段类型支持的多元化,json 类型的存储已成为多场景高频使用的字段类型。而 MySql、postgrpSql 等都支持json类型的存储,但 Mybatis 支持的基本类型中,是没有json类型的,需要单独配置 typeHandler 进行转换。
此文章会介绍在使用 Mybatis-Plus 的过程中,如何配置来实现对 json 类型的支持。
1、修改 pojo 中的注解
- 在类注解 @TableName 中,给 autoResultMap 设置属性值为 true(默认是false)
- 修改支持 json 存储的字段的注解,添加注解 @TableField(typeHandler = JacksonTypeHandler.class) , 此 typeHandler 为官方提供的,也可以自定义 Handler 实现类型转换

2、修改 mapper.xml 中的 resultMap
-
修改 mapper 中 resultMap 中映射的对应字段,也将 typeHandler 配置上

3、修改数据库连接,增加配置
在配置文件中,修改数据库的 url ,添加配置 stringtype=unspecified , 此配置用于数据支持特殊类型的转换

!!!若缺失此配置,将会出现如下报错
SQL: UPDATE viewing_angle SET name=?, destination=?, orientation=? WHERE id=?
### Cause: org.postgresql.util.PSQLException: ERROR: column "destination" is of type json but expression is of type character varying
建议:You will need to rewrite or cast the expression.
位置:48
; bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: ERROR: column "destination" is of type json but expression is of type character varying
建议:You will need to rewrite or cast the expression.
4、特别说明
截图中展示的 TestPerson.class 类,一定要实现序列化,实现 Serializable,否则会出现类型转换失败。
如果要实现 list -> json 的转换实现存储,就需要自定义 typeHandler 了,然后再配置到对应字段上就可以。

浙公网安备 33010602011771号