View Javadoc
1   /*
2    *    Copyright 2009-2023 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
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   * @author Clinton Begin
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(
79            "Cannot convert " + ordinal + " to " + type.getSimpleName() + " by ordinal value.", ex);
80      }
81    }
82  }