mybatis枚举类型处理器

1. 定义枚举值的接口

public abstract interface ValuedEnum {
    int getValue();
}
所有要被mybatis处理的枚举类继承该接口

2. 定义枚举类型,并实现ValuedEnum接口

public enum Gender implements ValuedEnum {
    UNKNOWN("保密", 0),
    MAIL("男", 1),
    FAMAIL("女", 2);

    private String name;
    private int value;

    Gender(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    @Override
    public int getValue() {
        return this.value;
    }
}

3. 继承mybatis的BaseTypeHandler抽象类

@MappedTypes(value = { Gender.class })
public class ValuedEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
    private final Map<Integer, E> map = new HashMap<>();

    public ValuedEnumTypeHandler(Class<E> type) {
        if (Objects.isNull(type)) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        E[] enums = type.getEnumConstants();
        if (Objects.isNull(enums)) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
        for (E e : enums) {
            ValuedEnum valuedEnum = (ValuedEnum) e;
            map.put(valuedEnum.getValue(), e);
        }
    }

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

    @Override
    public E getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        int i = resultSet.getInt(columnName);
        if (resultSet.wasNull()) {
            return null;
        } else {
            return map.get(i);
        }
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        int i = resultSet.getInt(columnIndex);
        if (resultSet.wasNull()) {
            return null;
        } else {
            return map.get(i);
        }
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        int i = callableStatement.getInt(columnIndex);
        if (callableStatement.wasNull()) {
            return null;
        } else {
            return map.get(i);
        }
    }
}

@MappedTypes注解表示ValuedEnumTypeHandler要处理的枚举类型

4. 在mybatis的配置文件中配置ValuedEnumTypeHandler

<typeHandlers>
        <typeHandler handler="com.example.ValuedEnumTypeHandler"/>
    </typeHandlers>

posted on 2017-12-16 09:48  jec  阅读(233)  评论(0编辑  收藏  举报

导航