一、前提概要
1.1 支持环境
数据库支持:MySql版本要求 5.7+
1.2 需求场景
使用MySQL数据库存储时,由于业务要求实体类中特定字段需要使用 自定义类型或者List、Map类型。
二、需求实现
2.1 非自定义数据类型,List、Map
首先:在需要转换的实体类字段上加上:
@TableField(typeHandler = JacksonTypeHandler.class)
接着:在该实体类上修改 @TableName
@TableName(value = "数据库表名",autoResultMap = true)
2.2 自定义类型数据类型
引入依赖:
<properties>
<jackson-core.version>2.12.6</jackson-core.version>
<jackson-databind.version>2.12.7.1</jackson-databind.version>
<jackson-annotations.version>2.15.2</jackson-annotations.version>
</properties>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-annotations.version}</version>
</dependency>
首先定义数据处理工具类:
@Component
public class ObjectToJackson {
private static ObjectMapper mapper;
@Resource
public void setMapper(ObjectMapper mapper) {
ObjectToJackson.mapper = mapper;
}
public static <T> String objectToJson(T o) {
try {
return ObjectToJackson.mapper.writeValueAsString(o);
} catch (Exception e) {
e.printStackTrace();
throw new ServerException(500);
}
}
public static <T> T jsonToObject(String s, TypeReference<T> typeReference) {
if (s == null) {
return null;
}
try {
return ObjectToJackson.mapper.readValue(s, typeReference);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new ServerException(500);
}
}
}
接着定义自己的转化规则:
public class ObjectToJacksonHandler extends BaseTypeHandler<Object> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
String json = ObjectToJackson.objectToJson(parameter);
ps.setString(i, json);
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
String string = rs.getString(columnName);
return ObjectToJackson.jsonToObject(string, new TypeReference<>() {
});
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String string = rs.getString(columnIndex);
return ObjectToJackson.jsonToObject(string, new TypeReference<>() {
});
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String string = cs.getString(columnIndex);
return ObjectToJackson.jsonToObject(string, new TypeReference<>() {
});
}
}
使用:
@TableName(value = "数据库表名", autoResultMap = true)
@TableField(typeHandler = ObjectToJacksonHandler.class)