支持对mybatis转对象过程中枚举类型自动转换.
声明: 最近发布的文章都是从已经上线的项目中分离的, 绝对经得起考验. 如有问题, 欢迎留言. 谢谢!
EnumTypeHandler.java
package com.xxx.xxx.config.mybatis;
import com.xxx.xxx.enums.BaseEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.*;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* mybatis枚举类型处理
* org.apache.ibatis.type.EnumOrdinalTypeHandler
* org.apache.ibatis.type.EnumTypeHandler
* @author Yehun
*/
@Slf4j
@MappedJdbcTypes(value = {JdbcType.NUMERIC, JdbcType.INTEGER})
public class EnumTypeHandler & BaseEnum> extends BaseTypeHandler> {
private Class type;
public EnumTypeHandler() { }
/**
* 设置配置文件设置的转换类以及枚举类内容
* @param type 配置文件中设置的转换类
*/
public EnumTypeHandler(Class type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
Integer code = parameter.getCode();
if (jdbcType == null && code != null) {
ps.setInt(i, code);
} else {
assert jdbcType != null;
ps.setObject(i, parameter.getCode(), jdbcType.TYPE_CODE); // see r3589
}
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
Integer i = rs.getInt(columnName);
return rs.wasNull() ? null : getEnum(i);
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Integer i = rs.getInt(columnIndex);
return rs.wasNull() ? null : getEnum(i);
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Integer i = cs.getInt(columnIndex);
return cs.wasNull() ? null : getEnum(i);
}
/**
* 枚举类型转换,由于构造函数获取了枚举的子类enums
* @param value 数据库中存储的自定义value属性
* @return value对应的枚举类
*/
private E getEnum(Integer value) {
log.debug("enum is [{}]", this.type.getName());
E[] enums = this.type.getEnumConstants();
if(enums != null) {
for (E e : enums) {
if (e.getCode().equals(value)) {
return e;
}
}
}
throw new IllegalArgumentException(String.format("未知的枚举类型:%s,请核对%s", value, type.getSimpleName()));
}
}
在mybatis-config.xml中置顶转换
ok