|
@@ -19,16 +19,11 @@ import com.baomidou.mybatisplus.core.toolkit.Assert;
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
-import org.apache.ibatis.type.BaseTypeHandler;
|
|
|
import org.apache.ibatis.type.JdbcType;
|
|
|
import org.apache.ibatis.type.MappedJdbcTypes;
|
|
|
import org.apache.ibatis.type.MappedTypes;
|
|
|
|
|
|
import java.io.IOException;
|
|
|
-import java.sql.CallableStatement;
|
|
|
-import java.sql.PreparedStatement;
|
|
|
-import java.sql.ResultSet;
|
|
|
-import java.sql.SQLException;
|
|
|
|
|
|
/**
|
|
|
* Jackson 实现 JSON 字段类型处理器
|
|
@@ -39,8 +34,8 @@ import java.sql.SQLException;
|
|
|
@Slf4j
|
|
|
@MappedTypes({Object.class})
|
|
|
@MappedJdbcTypes(JdbcType.VARCHAR)
|
|
|
-public class JacksonTypeHandler extends BaseTypeHandler<Object> {
|
|
|
- private ObjectMapper objectMapper = new ObjectMapper();
|
|
|
+public class JacksonTypeHandler extends AbstractJsonTypeHandler<Object> {
|
|
|
+ private static ObjectMapper objectMapper = new ObjectMapper();
|
|
|
private Class<Object> type;
|
|
|
|
|
|
public JacksonTypeHandler(Class<Object> type) {
|
|
@@ -51,42 +46,26 @@ public class JacksonTypeHandler extends BaseTypeHandler<Object> {
|
|
|
this.type = type;
|
|
|
}
|
|
|
|
|
|
- private Object parse(String json) {
|
|
|
+ public static void setObjectMapper(ObjectMapper objectMapper) {
|
|
|
+ Assert.notNull(objectMapper, "ObjectMapper should not be null");
|
|
|
+ JacksonTypeHandler.objectMapper = objectMapper;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ protected Object parse(String json) {
|
|
|
try {
|
|
|
- if (json == null || json.length() == 0) {
|
|
|
- return null;
|
|
|
- }
|
|
|
return objectMapper.readValue(json, type);
|
|
|
} catch (IOException e) {
|
|
|
throw new RuntimeException(e);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- private String toJsonString(Object obj) {
|
|
|
+ @Override
|
|
|
+ protected String toJson(Object obj) {
|
|
|
try {
|
|
|
return objectMapper.writeValueAsString(obj);
|
|
|
} catch (JsonProcessingException e) {
|
|
|
throw new RuntimeException(e);
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
- @Override
|
|
|
- public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
|
|
- return parse(rs.getString(columnName));
|
|
|
- }
|
|
|
-
|
|
|
- @Override
|
|
|
- public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
|
|
- return parse(rs.getString(columnIndex));
|
|
|
- }
|
|
|
-
|
|
|
- @Override
|
|
|
- public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
|
|
- return parse(cs.getString(columnIndex));
|
|
|
- }
|
|
|
-
|
|
|
- @Override
|
|
|
- public void setNonNullParameter(PreparedStatement ps, int columnIndex, Object parameter, JdbcType jdbcType) throws SQLException {
|
|
|
- ps.setString(columnIndex, toJsonString(parameter));
|
|
|
- }
|
|
|
}
|