Mybatis存取数据格式转换
2020-10-27 本文已影响0人
周_0717
使用举例:
@TableField(typeHandler = StringListTypeHandler.class)
private List<String> topList;
-
对需要转换类型的字段添加TableField注解指定对应执行当class(这个class一定要是对应此字段class类型的构造函数)
-
别忘了在配置文件中配置转换文件所在包的位置
mybatis-plus.type-handlers-package: com.zpf.demo.global.handler
- TypeHanlder源码:
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected 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));
}
protected String toJsonString(Object parameter) {
try {
return objectMapper.writeValueAsString(parameter);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
protected T parse(String json) {
try {
return objectMapper.readValue(json, type);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
public class StringListTypeHandler extends JsonTypeHandler<List<String>> {
public StringListTypeHandler(Class<List<String>> type) {
super(type);
}
@Override
protected List<String> parse(String json) {
try {
return objectMapper.readValue(json, type);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
其中MappedJdbcTypes注解描述对应数据库字段类型,MappedTypes注解描述转换字段类型了;
2020-10-08