001/*
002 *  Copyright (c) 2022-2025, 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.lang.reflect.Method;
026import java.sql.CallableStatement;
027import java.sql.PreparedStatement;
028import java.sql.ResultSet;
029import java.sql.SQLException;
030import java.util.Arrays;
031import java.util.List;
032import java.util.stream.Collectors;
033
034public class CompositeEnumTypeHandler<E extends Enum<E>> implements TypeHandler<E> {
035
036    private final TypeHandler<E> delegate;
037
038    public CompositeEnumTypeHandler(Class<E> enumClass) {
039        boolean isNotFound = false;
040        List<Field> enumDbValueFields = ClassUtil.getAllFields(enumClass, f -> f.getAnnotation(EnumValue.class) != null);
041        if (enumDbValueFields.isEmpty()) {
042            Method enumDbValueMethod = ClassUtil.getFirstMethodByAnnotation(enumClass, EnumValue.class);
043            if (enumDbValueMethod == null) {
044                isNotFound = true;
045            }
046        }
047        if (isNotFound) {
048            delegate = new EnumTypeHandler<>(enumClass);
049        } else {
050            delegate = new FlexEnumTypeHandler<>(enumClass);
051        }
052    }
053
054    @Override
055    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
056        delegate.setParameter(ps, i, parameter, jdbcType);
057    }
058
059    @Override
060    public E getResult(ResultSet rs, String columnName) throws SQLException {
061        return delegate.getResult(rs, columnName);
062    }
063
064    @Override
065    public E getResult(ResultSet rs, int columnIndex) throws SQLException {
066        return delegate.getResult(rs, columnIndex);
067    }
068
069    @Override
070    public E getResult(CallableStatement cs, int columnIndex) throws SQLException {
071        return delegate.getResult(cs, columnIndex);
072    }
073
074}