在编码过程当中,常常会遇到用某个数值来表示某种状态、类型或者阶段的状况,好比有这样一个枚举:java
public enum ComputerState { OPEN(10), //开启 CLOSE(11), //关闭 OFF_LINE(12), //离线 FAULT(200), //故障 UNKNOWN(255); //未知 private int code; ComputerState(int code) { this.code = code; } }
一般咱们但愿将表示状态的数值存入数据库,即ComputerState.OPEN
存入数据库取值为10
。sql
首先,咱们先看看MyBatis是否可以知足咱们的需求。 MyBatis内置了两个枚举转换器分别是:org.apache.ibatis.type.EnumTypeHandler
和org.apache.ibatis.type.EnumOrdinalTypeHandler
。数据库
这是默认的枚举转换器,该转换器将枚举实例转换为实例名称的字符串,即将ComputerState.OPEN
转换OPEN
。apache
顾名思义这个转换器将枚举实例的ordinal属性做为取值,即ComputerState.OPEN
转换为0
,ComputerState.CLOSE
转换为1
。 使用它的方式是在MyBatis配置文件中定义:segmentfault
<typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.example.entity.enums.ComputerState"/> </typeHandlers>
以上的两种转换器都不能知足咱们的需求,因此看起来要本身编写一个转换器了。mybatis
MyBatis提供了org.apache.ibatis.type.BaseTypeHandler
类用于咱们本身扩展类型转换器,上面的EnumTypeHandler
和EnumOrdinalTypeHandler
也都实现了这个接口。app
咱们须要一个接口来肯定某部分枚举类的行为。以下:ide
public interface BaseCodeEnum { int getCode(); }
该接口只有一个返回编码的方法,返回值将被存入数据库。工具
就拿上面的ComputerState
来实现BaseCodeEnum
接口:测试
public enum ComputerState implements BaseCodeEnum{ OPEN(10), //开启 CLOSE(11), //关闭 OFF_LINE(12), //离线 FAULT(200), //故障 UNKNOWN(255); //未知 private int code; ComputerState(int code) { this.code = code; } @Override public int getCode() { return this.code; } }
如今咱们能顺利的将枚举转换为某个数值了,还须要一个工具将数值转换为枚举实例。
public class CodeEnumUtil { public static <E extends Enum<?> & BaseCodeEnum> E codeOf(Class<E> enumClass, int code) { E[] enumConstants = enumClass.getEnumConstants(); for (E e : enumConstants) { if (e.getCode() == code) return e; } return null; } }
准备工做作的差很少了,是时候开始编写转换器了。 BaseTypeHandler<T>
一共须要实现4个方法:
void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType)
用于定义设置参数时,该如何把Java类型的参数转换为对应的数据库类型T getNullableResult(ResultSet rs, String columnName)
用于定义经过字段名称获取字段数据时,如何把数据库类型转换为对应的Java类型T getNullableResult(ResultSet rs, int columnIndex)
用于定义经过字段索引获取字段数据时,如何把数据库类型转换为对应的Java类型T getNullableResult(CallableStatement cs, int columnIndex)
用定义调用存储过程后,如何把数据库类型转换为对应的Java类型我是这样实现的:
public class CodeEnumTypeHandler<E extends Enum<?> & BaseCodeEnum> extends BaseTypeHandler<BaseCodeEnum> { private Class<E> type; public CodeEnumTypeHandler(Class<E> type) { if (type == null) { throw new IllegalArgumentException("Type argument cannot be null"); } this.type = type; } @Override public void setNonNullParameter(PreparedStatement ps, int i, BaseCodeEnum parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, parameter.getCode()); } @Override public E getNullableResult(ResultSet rs, String columnName) throws SQLException { int i = rs.getInt(columnName); if (rs.wasNull()) { return null; } else { try { return CodeEnumUtil.codeOf(type, i); } catch (Exception ex) { throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex); } } } @Override public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException { int i = rs.getInt(columnIndex); if (rs.wasNull()) { return null; } else { try { return CodeEnumUtil.codeOf(type, i); } catch (Exception ex) { throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex); } } } @Override public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { int i = cs.getInt(columnIndex); if (cs.wasNull()) { return null; } else { try { return CodeEnumUtil.codeOf(type, i); } catch (Exception ex) { throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex); } } } }
接下来须要指定哪一个类使用咱们本身编写转换器进行转换,在MyBatis配置文件中配置以下:
<typeHandlers> <typeHandler handler="com.example.typeHandler.CodeEnumTypeHandler" javaType="com.example.entity.enums.ComputerState"/> </typeHandlers>
搞定! 经测试ComputerState.OPEN
被转换为10
,ComputerState.UNKNOWN
被转换为255
,达到了预期的效果。
在第5步时,咱们在MyBatis中添加typeHandler
用于指定哪些类使用咱们自定义的转换器,一旦系统中的枚举类多了起来,MyBatis的配置文件维护起来会变得很是麻烦,也容易出错。如何解决呢? 在Spring
中咱们可使用JavaConfig
方式来干预SqlSessionFactory
的建立过程,来完成动态的转换器指定。 思路
sqlSessionFactory.getConfiguration().getTypeHandlerRegistry()
取得类型转换器注册器BaseCodeEnum
接口的枚举类BaseCodeEnum
的类注册使用CodeEnumTypeHandler
进行转换。实现以下:
MyBatisConfig.java
@Configuration @ConfigurationProperties(prefix = "mybatis") public class MyBatisConfig { private String configLocation; private String mapperLocations; @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourcesUtil resourcesUtil) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 设置配置文件地址 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setConfigLocation(resolver.getResource(configLocation)); factory.setMapperLocations(resolver.getResources(mapperLocations)); SqlSessionFactory sqlSessionFactory = factory.getObject(); // ----------- 动态加载实现BaseCodeEnum接口的枚举,使用CodeEnumTypeHandler转换器 // 取得类型转换注册器 TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); // 扫描全部实体类 List<String> classNames = resourcesUtil.list("com/example", "/**/entity"); for (String className : classNames) { // 处理路径成为类名 className = className.replace('/', '.').replaceAll("\\.class", ""); // 取得Class Class<?> aClass = Class.forName(className, false, getClass().getClassLoader()); // 判断是否实现了BaseCodeEnum接口 if (aClass.isEnum() && BaseCodeEnum.class.isAssignableFrom(aClass)) { // 注册 typeHandlerRegistry.register(className, "com.example.typeHandler.CodeEnumTypeHandler"); } } // --------------- end return sqlSessionFactory; } public String getConfigLocation() { return configLocation; } public void setConfigLocation(String configLocation) { this.configLocation = configLocation; } public String getMapperLocations() { return mapperLocations; } public void setMapperLocations(String mapperLocations) { this.mapperLocations = mapperLocations; } }
ResourcesUtil.java
@Component public class ResourcesUtil { private final ResourcePatternResolver resourceResolver; public ResourcesUtil() { this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); } /** * 返回路径下全部class * * @param rootPath 根路径 * @param locationPattern 位置表达式 * @return * @throws IOException */ public List<String> list(String rootPath, String locationPattern) throws IOException { Resource[] resources = resourceResolver.getResources("classpath*:" + rootPath + locationPattern + "/**/*.class"); List<String> resourcePaths = new ArrayList<>(); for (Resource resource : resources) { resourcePaths.add(preserveSubpackageName(resource.getURI(), rootPath)); } return resourcePaths; } }
以上就是我对如何在MyBatis中优雅的使用枚举的探索。若是你还有更优的解决方案,请必定在评论中告知,万分感激。