背景:
目前公司的一个SpringBoot项目,有一张表的一个字段需要存储枚举,之前保存的一直是枚举的code值,导致实体类的该属性是int类型,而不是枚举类型。技术领导希望我能解决这个问题,思路很简单,从网上找一下 “mybatis枚举自动转换”,应该不难。
结果:
但是看过大部分文章后,发现在 通用的自动转换 时,有点麻烦,大部分都建议枚举实现一个接口或在转换类中表明转换哪些枚举。经常仔细查看代码,根据我们项目的实际情况。编写出 枚举通用转换类,仅供参考。
废话不多说,直接上代码:
AutoEnumTypeHandler.class
package com.founderbn.common.mybatis.typeHandler;
import com.founderbn.common.mybatis.constants.EnumTransfer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
public class AutoEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
private Class<E> type;
public AutoEnumTypeHandler(Class<E> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
} else {
EnumTransfer transfer = (EnumTransfer)type.getAnnotation(EnumTransfer.class);
if (transfer == null) {
throw new RuntimeException(type.getSimpleName() + " 没有使用@EnumT