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; }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM