1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.submitted.enum_interface_type_handler;
17
18 import java.sql.CallableStatement;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22
23 import org.apache.ibatis.type.BaseTypeHandler;
24 import org.apache.ibatis.type.JdbcType;
25 import org.apache.ibatis.type.MappedTypes;
26
27 @MappedTypes(HasValue.class)
28 public class HasValueEnumTypeHandler<E extends Enum<E> & HasValue> extends BaseTypeHandler<E> {
29 private Class<E> type;
30 private final E[] enums;
31
32 public HasValueEnumTypeHandler(Class<E> type) {
33 if (type == null) {
34 throw new IllegalArgumentException("Type argument cannot be null");
35 }
36 this.type = type;
37 this.enums = type.getEnumConstants();
38 if (!type.isInterface() && this.enums == null) {
39 throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
40 }
41 }
42
43 @Override
44 public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
45 ps.setInt(i, parameter.getValue());
46 }
47
48 @Override
49 public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
50 int value = rs.getInt(columnName);
51 if (rs.wasNull()) {
52 return null;
53 }
54 for (E enm : enums) {
55 if (value == enm.getValue()) {
56 return enm;
57 }
58 }
59 throw new IllegalArgumentException("Cannot convert " + value + " to " + type.getSimpleName());
60 }
61
62 @Override
63 public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
64 int value = rs.getInt(columnIndex);
65 if (rs.wasNull()) {
66 return null;
67 }
68 for (E enm : enums) {
69 if (value == enm.getValue()) {
70 return enm;
71 }
72 }
73 throw new IllegalArgumentException("Cannot convert " + value + " to " + type.getSimpleName());
74 }
75
76 @Override
77 public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
78 int value = cs.getInt(columnIndex);
79 if (cs.wasNull()) {
80 return null;
81 }
82 for (E enm : enums) {
83 if (value == enm.getValue()) {
84 return enm;
85 }
86 }
87 throw new IllegalArgumentException("Cannot convert " + value + " to " + type.getSimpleName());
88 }
89 }