All Downloads are FREE. Search and download functionalities are using the official Maven repository.

mybatis.handler.AbstractCodeEnumTypeHandler Maven / Gradle / Ivy

The newest version!
package mybatis.handler;

import com.itcoon.common.core.enums.CodeEnum;
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;
import java.util.Arrays;

public abstract class AbstractCodeEnumTypeHandler & CodeEnum> extends BaseTypeHandler {

    private final Class type;

    public AbstractCodeEnumTypeHandler(Class type) {
        if(type == null){
            throw new IllegalArgumentException("Enum class can not be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, e.value());
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        int code = resultSet.getInt(columnLabel);
        return getCodeEnumfromCode(code);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        int code = resultSet.getInt(columnIndex);
        return getCodeEnumfromCode(code);
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        int code = callableStatement.getInt(columnIndex);
        return getCodeEnumfromCode(code);
    }

    private E getCodeEnumfromCode(int code) throws SQLException {
        try {
            return Arrays.stream(type.getEnumConstants()).filter(codeEnum->codeEnum.value().equals(code)).findAny().orElseThrow(()->new IllegalArgumentException("column value illegal, can not read as Enum#"+type.getSimpleName()));
        } catch (IllegalArgumentException e) {
            throw new SQLException(e.getMessage());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy