package com.cainiao.aeye.chdir.manager.tddl.Handler;

import com.cainiao.aeye.chdir.core.enums.AudioFormatEnum;import org.apache.commons.lang3.StringUtils;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;

/** * @Auther:wb-fem407232 */public class EnumAudioFormatHandler extends BaseTypeHandler<AudioFormatEnum> {    private final AudioFormatEnum[] enums;    private Class<AudioFormatEnum> type;

    /**     * 设置配置文件设置的转换类以及枚举类内容,供其他方法更便捷高效的实现     *     * @param type 配置文件中设置的转换类     */    public EnumAudioFormatHandler(Class<AudioFormatEnum> type) {        if (type == null) {            throw new IllegalArgumentException("Type argument cannot be null");        }        this.type = type;        this.enums = type.getEnumConstants();        if (this.enums == null) {            throw new IllegalArgumentException(type.getSimpleName()                    + " does not represent an enum type.");        }    }

    @Override    public void setNonNullParameter(PreparedStatement preparedStatement, int i, AudioFormatEnum audioFormatEnum, JdbcType jdbcType) throws SQLException {        preparedStatement.setString(i, audioFormatEnum.name());    }

    @Override    public AudioFormatEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {        String name = resultSet.getString(s);        if (resultSet.wasNull()) {            return null;        } else {            return locateEnumStatus(name);        }    }

    @Override    public AudioFormatEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {        String name = resultSet.getString(i);        if (resultSet.wasNull()) {            return null;        } else {            return locateEnumStatus(name);        }    }

    @Override    public AudioFormatEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {        String name = callableStatement.getString(i);        if (callableStatement.wasNull()) {            return null;        } else {            return locateEnumStatus(name);        }    }

    /**     * 枚举类型转换,由于构造函数获取了枚举的子类enums,让遍历更加高效快捷     *     * @param name 数据库中存储的自定义code属性     * @return code对应的枚举类     */    private AudioFormatEnum locateEnumStatus(String name) {        if(StringUtils.isBlank(name)){            return null;        }        for (AudioFormatEnum status : enums) {            if (status.name().equals(name)) {                return status;            }        }        throw new IllegalArgumentException("未知的枚举类型:" + name + ",请核对" + type.getSimpleName());    }}
05-07 10:02