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.annotation.EnumValue;
019import com.mybatisflex.core.util.ClassUtil;
020import org.apache.ibatis.type.EnumTypeHandler;
021import org.apache.ibatis.type.JdbcType;
022import org.apache.ibatis.type.TypeHandler;
023
024import java.lang.reflect.Field;
025import java.sql.CallableStatement;
026import java.sql.PreparedStatement;
027import java.sql.ResultSet;
028import java.sql.SQLException;
029import java.util.List;
030
031public class CompositeEnumTypeHandler<E extends Enum<E>> implements TypeHandler<E> {
032
033    private final TypeHandler<E> delegate;
034
035    public CompositeEnumTypeHandler(Class<E> enumClass) {
036        List<Field> enumDbValueFields = ClassUtil.getAllFields(enumClass, f -> f.getAnnotation(EnumValue.class) != null);
037        if (enumDbValueFields.isEmpty()) {
038            delegate = new EnumTypeHandler<>(enumClass);
039        } else {
040            delegate = new FlexEnumTypeHandler<>(enumClass);
041        }
042    }
043
044    @Override
045    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
046        delegate.setParameter(ps, i, parameter, jdbcType);
047    }
048
049    @Override
050    public E getResult(ResultSet rs, String columnName) throws SQLException {
051        return delegate.getResult(rs, columnName);
052    }
053
054    @Override
055    public E getResult(ResultSet rs, int columnIndex) throws SQLException {
056        return delegate.getResult(rs, columnIndex);
057    }
058
059    @Override
060    public E getResult(CallableStatement cs, int columnIndex) throws SQLException {
061        return delegate.getResult(cs, columnIndex);
062    }
063
064}