MyBatis-Plus自定義TypeHandler轉換Json
阿新 • • 發佈:2020-09-22
原文連結: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;
}