Mybatis枚举转换
自定义mybatis枚举转换,原理是如果用户没有定义自己的枚举转换工具,mybatis在解析枚举类时会自动获取mybatis的BaseTypeHandler,来转换枚举类,我们只需要重写这个枚举转换器,并将它指定为默认的转换器就好了
首先,定义一个通用接口BaseEnum:
import java.util.Arrays;
import java.util.Optional;
public interface BaseEnum<T>{
T getDictKey();
default T getValue() {
return this.getDictKey();
}
static <T> BaseEnum valueOfEnum(Class<BaseEnum> enumClass, T value){
if (value == null){
return null;
}
BaseEnum[] enums = enumClass.getEnumConstants();
Optional<BaseEnum> optional = Arrays.asList(enums).stream().filter(baseEnum -> baseEnum.getDictKey().equals(value)).findAny();
if (optional.isPresent()){
return optional.get();
}
throw new RuntimeException("未找到:" + value + "对应的" + enumClass.getName());
}
}
然后,定义一个枚举解析器MyEnumTypeHandler,该枚举类继承自BaseTypeHandler:
import com.bluepay.spring.mybatis.demo.BaseEnum;
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;
public class MyEnumTypeHandler<T> extends BaseTypeHandler<BaseEnum<T>> {
private final Class<BaseEnum> type;
public MyEnumTypeHandler(Class<BaseEnum> type) {
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
System.out.println("set value");
if (jdbcType == null) {
ps.setString(i, (String) parameter.getDictKey());
} else {
ps.setObject(i, parameter.getDictKey(), jdbcType.TYPE_CODE); // see r3589
}
}
@Override
public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
String s = rs.getString(columnName);
return s == null ? null : BaseEnum.valueOfEnum(type, s);
}
@Override
public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String s = rs.getString(columnIndex);
return s == null ? null : BaseEnum.valueOfEnum(type, s);
}
@Override
public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String s = cs.getString(columnIndex);
return s == null ? null : BaseEnum.valueOfEnum(type, s);
}
}
最后,将该枚举解析器配置为mybatis的默认枚举解析器,mybatis-config.xml配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeHandlers>
<typeHandler handler="com.bluepay.spring.mybatis.config.MyEnumTypeHandler" javaType="com.bluepay.spring.mybatis.demo.BaseEnum"></typeHandler>
</typeHandlers>
</configuration>
至此,默认的枚举转换类型定义完成,用户的枚举类只要实现BaseEnum接口,就可以被正确的解析了