EnumOrdinalTypeHandler.java

  1. /*
  2.  *    Copyright 2009-2024 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. import java.sql.CallableStatement;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.sql.SQLException;

  21. /**
  22.  * @author Clinton Begin
  23.  */
  24. public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

  25.   private final Class<E> type;
  26.   private final E[] enums;

  27.   public EnumOrdinalTypeHandler(Class<E> type) {
  28.     if (type == null) {
  29.       throw new IllegalArgumentException("Type argument cannot be null");
  30.     }
  31.     this.type = type;
  32.     this.enums = type.getEnumConstants();
  33.     if (this.enums == null) {
  34.       throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
  35.     }
  36.   }

  37.   @Override
  38.   public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
  39.     ps.setInt(i, parameter.ordinal());
  40.   }

  41.   @Override
  42.   public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
  43.     int ordinal = rs.getInt(columnName);
  44.     if (ordinal == 0 && rs.wasNull()) {
  45.       return null;
  46.     }
  47.     return toOrdinalEnum(ordinal);
  48.   }

  49.   @Override
  50.   public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
  51.     int ordinal = rs.getInt(columnIndex);
  52.     if (ordinal == 0 && rs.wasNull()) {
  53.       return null;
  54.     }
  55.     return toOrdinalEnum(ordinal);
  56.   }

  57.   @Override
  58.   public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  59.     int ordinal = cs.getInt(columnIndex);
  60.     if (ordinal == 0 && cs.wasNull()) {
  61.       return null;
  62.     }
  63.     return toOrdinalEnum(ordinal);
  64.   }

  65.   private E toOrdinalEnum(int ordinal) {
  66.     try {
  67.       return enums[ordinal];
  68.     } catch (Exception ex) {
  69.       throw new IllegalArgumentException(
  70.           "Cannot convert " + ordinal + " to " + type.getSimpleName() + " by ordinal value.", ex);
  71.     }
  72.   }
  73. }