|
@@ -0,0 +1,52 @@
|
|
1
|
+package com.unis.framework.mybatis.core.type;
|
|
2
|
+
|
|
3
|
+import com.fasterxml.jackson.core.JsonProcessingException;
|
|
4
|
+import com.fasterxml.jackson.core.type.TypeReference;
|
|
5
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
6
|
+import org.apache.ibatis.type.BaseTypeHandler;
|
|
7
|
+import org.apache.ibatis.type.JdbcType;
|
|
8
|
+import java.sql.CallableStatement;
|
|
9
|
+import java.sql.PreparedStatement;
|
|
10
|
+import java.sql.ResultSet;
|
|
11
|
+import java.sql.SQLException;
|
|
12
|
+import java.util.Collections;
|
|
13
|
+import java.util.List;
|
|
14
|
+
|
|
15
|
+public class JsonToListTypeHandler extends BaseTypeHandler<List<String>> {
|
|
16
|
+ private static final ObjectMapper mapper = new ObjectMapper();
|
|
17
|
+
|
|
18
|
+ @Override
|
|
19
|
+ public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
|
|
20
|
+ try {
|
|
21
|
+ ps.setString(i, mapper.writeValueAsString(parameter));
|
|
22
|
+ } catch (JsonProcessingException e) {
|
|
23
|
+ throw new SQLException("JSON序列化失败", e);
|
|
24
|
+ }
|
|
25
|
+ }
|
|
26
|
+
|
|
27
|
+ @Override
|
|
28
|
+ public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
|
29
|
+ return parseJsonToList(rs.getString(columnName));
|
|
30
|
+ }
|
|
31
|
+
|
|
32
|
+ @Override
|
|
33
|
+ public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
|
34
|
+ return parseJsonToList(rs.getString(columnIndex));
|
|
35
|
+ }
|
|
36
|
+
|
|
37
|
+ @Override
|
|
38
|
+ public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
|
39
|
+ return parseJsonToList(cs.getString(columnIndex));
|
|
40
|
+ }
|
|
41
|
+
|
|
42
|
+ private List<String> parseJsonToList(String json) {
|
|
43
|
+ if (json == null || json.isEmpty()) {
|
|
44
|
+ return Collections.emptyList();
|
|
45
|
+ }
|
|
46
|
+ try {
|
|
47
|
+ return mapper.readValue(json, new TypeReference<List<String>>() {});
|
|
48
|
+ } catch (JsonProcessingException e) {
|
|
49
|
+ throw new RuntimeException("JSON解析失败", e);
|
|
50
|
+ }
|
|
51
|
+ }
|
|
52
|
+}
|