EnumTypeHandler.java

  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. 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 EnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

  25.   private final Class<E> type;

  26.   public EnumTypeHandler(Class<E> type) {
  27.     if (type == null) {
  28.       throw new IllegalArgumentException("Type argument cannot be null");
  29.     }
  30.     this.type = type;
  31.   }

  32.   @Override
  33.   public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
  34.     if (jdbcType == null) {
  35.       ps.setString(i, parameter.name());
  36.     } else {
  37.       ps.setObject(i, parameter.name(), jdbcType.TYPE_CODE); // see r3589
  38.     }
  39.   }

  40.   @Override
  41.   public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
  42.     String s = rs.getString(columnName);
  43.     return s == null ? null : Enum.valueOf(type, s);
  44.   }

  45.   @Override
  46.   public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
  47.     String s = rs.getString(columnIndex);
  48.     return s == null ? null : Enum.valueOf(type, s);
  49.   }

  50.   @Override
  51.   public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  52.     String s = cs.getString(columnIndex);
  53.     return s == null ? null : Enum.valueOf(type, s);
  54.   }
  55. }