001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.handler; 017 018import com.mybatisflex.core.util.EnumWrapper; 019import org.apache.ibatis.type.BaseTypeHandler; 020import org.apache.ibatis.type.JdbcType; 021 022import java.sql.CallableStatement; 023import java.sql.PreparedStatement; 024import java.sql.ResultSet; 025import java.sql.SQLException; 026 027public class FlexEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> { 028 029 private EnumWrapper<E> enumWrapper; 030 031 public FlexEnumTypeHandler(Class<E> enumClass) { 032 enumWrapper = EnumWrapper.of(enumClass); 033 } 034 035 036 @Override 037 public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException { 038 Object value = enumWrapper.getEnumValue(parameter); 039 if (jdbcType == null) { 040 ps.setObject(i, value); 041 } else { 042 ps.setObject(i, value, jdbcType.TYPE_CODE); 043 } 044 } 045 046 @Override 047 public E getNullableResult(ResultSet rs, String columnName) throws SQLException { 048 Object value = rs.getObject(columnName, enumWrapper.getPropertyType()); 049 if (null == value && rs.wasNull()) { 050 return null; 051 } 052 return enumWrapper.getEnum(value); 053 } 054 055 056 @Override 057 public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException { 058 Object value = rs.getObject(columnIndex, enumWrapper.getPropertyType()); 059 if (null == value && rs.wasNull()) { 060 return null; 061 } 062 return enumWrapper.getEnum(value); 063 } 064 065 066 @Override 067 public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { 068 Object value = cs.getObject(columnIndex, enumWrapper.getPropertyType()); 069 if (null == value && cs.wasNull()) { 070 return null; 071 } 072 return enumWrapper.getEnum(value); 073 } 074 075 076}