MyBatis-Plus自定义TypeHandler转换Json
原文链接:https://www.jianshu.com/p/57c01e1b3c63
0x0 背景
在项目开发中,我们有时会将一些属性作为json字符串保存到数据库,此时如何优雅的使用mybatis进行存储和查询就成为一个问题。
mybatis提供了TypeHandler接口可供用户进行自定义属性转换逻辑,本文基于mybatis-plus,写一个demo便于大家参考。
0x1 代码
首先是我们的主角:JsonTypeHandler
,该类作为父类使用(因为不知道具体的反序列化类是什么)
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
private static ObjectMapper objectMapper = new ObjectMapper();
private Class<T> type;
public JsonTypeHandler(Class<T> type) {
if (type == null) {
throw new NullPointerException("Type argument cannot be null");
}
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, toJsonString(parameter));
}
@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parse(rs.getString(columnName));
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parse(rs.getString(columnIndex));
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parse(cs.getString(columnIndex));
}
private String toJsonString(Object parameter) {
try {
return objectMapper.writeValueAsString(parameter);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private T parse(String json) {
try {
return objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
然后我们针对具体的类,继承一个实际处理类,如下(我们的实体类名为User):
public class UserTypeHandler extends JsonTypeHandler<User> {
public UserTypeHandler() {
super(User.class);
}
}
接下来在我们的实体类中,对应的字段上加注解:
@Data
@Accessors(chain = true)
//注意这里,要加autoResultMap = true
@TableName(value = "tb_department", autoResultMap = true)
public class DataSourceInfo {
@TableId(type = IdType.AUTO)
private Long id;
private String type;
//指定具体的处理器
@TableField(typeHandler = UserTypeHandler.class)
private User user;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)