0x0 背景
在项目开发中,我们有时会将一些属性作为json字符串保存到数据库,此时如何优雅的使用mybatis进行存储和查询就成为一个问题。
mybatis提供了TypeHandler接口可供用户进行自定义属性转换逻辑,本文基于mybatis-plus,写一个demo便于大家参考。
0x1 代码
首先是我们的主角:JsonTypeHandler,该类作为父类使用(因为不知道具体的反序列化类是什么)
public class JsonTypeHandler extends BaseTypeHandler {
private static ObjectMapper objectMapper = new ObjectMapper();
private Class type;
public JsonTypeHandler(Class 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 getNullableR