1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.submitted.typebasedtypehandlerresolution;
17
18 import java.lang.reflect.ParameterizedType;
19 import java.lang.reflect.Type;
20 import java.sql.CallableStatement;
21 import java.sql.PreparedStatement;
22 import java.sql.ResultSet;
23 import java.sql.SQLException;
24 import java.util.List;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27
28 import org.apache.ibatis.type.BaseTypeHandler;
29 import org.apache.ibatis.type.JdbcType;
30 import org.assertj.core.util.Arrays;
31
32 public class CsvTypeHandler extends BaseTypeHandler<Object> {
33 private final Type type;
34
35 public CsvTypeHandler(Type type) {
36 super();
37 this.type = type;
38 }
39
40 @SuppressWarnings({ "unchecked", "rawtypes" })
41 @Override
42 public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
43 throws SQLException {
44
45 if (parameter instanceof List) {
46 Class<?> elementClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
47 if (String.class.equals(elementClass)) {
48 ps.setString(i, String.join(",", (List) parameter));
49 } else if (Integer.class.equals(elementClass)) {
50 ps.setString(i, (String) ((List) parameter).stream().map(String::valueOf).collect(Collectors.joining(",")));
51 }
52 }
53 }
54
55 @Override
56 public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
57 String str = rs.getString(columnName);
58 if (str == null) {
59 return null;
60 }
61 if (type instanceof ParameterizedType) {
62 Type argType = ((ParameterizedType) type).getActualTypeArguments()[0];
63 if (argType instanceof Class) {
64 if (String.class.equals(argType)) {
65 return Arrays.asList(str.split(","));
66 } else if (Integer.class.equals(argType)) {
67 return Stream.of(str.split(",")).map(Integer::valueOf).collect(Collectors.toList());
68 }
69 }
70 }
71 return null;
72 }
73
74 @Override
75 public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
76
77 return null;
78 }
79
80 @Override
81 public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
82
83 return null;
84 }
85
86 }