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