博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在MyBatis中优雅的使用枚举
阅读量:4582 次
发布时间:2019-06-09

本文共 6638 字,大约阅读时间需要 22 分钟。

问题

在编码过程中,经常会遇到用某个数值来表示某种状态、类型或者阶段的情况,比如有这样一个枚举:

 
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

探索

首先,我们先看看MyBatis是否能够满足我们的需求。 MyBatis内置了两个枚举转换器分别是:org.apache.ibatis.type.EnumTypeHandlerorg.apache.ibatis.type.EnumOrdinalTypeHandler

EnumTypeHandler

这是默认的枚举转换器,该转换器将枚举实例转换为实例名称的字符串,即将ComputerState.OPEN转换OPEN

EnumOrdinalTypeHandler

顾名思义这个转换器将枚举实例的ordinal属性作为取值,即ComputerState.OPEN转换为0,ComputerState.CLOSE转换为1。 使用它的方式是在MyBatis配置文件中定义:

 

以上的两种转换器都不能满足我们的需求,所以看起来要自己编写一个转换器了。

方案

MyBatis提供了org.apache.ibatis.type.BaseTypeHandler类用于我们自己扩展类型转换器,上面的EnumTypeHandlerEnumOrdinalTypeHandler也都实现了这个接口。

1. 定义接口

我们需要一个接口来确定某部分枚举类的行为。如下:

 
public interface BaseCodeEnum {    int getCode(); }

该接口只有一个返回编码的方法,返回值将被存入数据库。

2. 改造枚举

就拿上面的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; } }

3. 编写一个转换工具类

现在我们能顺利的将枚举转换为某个数值了,还需要一个工具将数值转换为枚举实例。

 
public class CodeEnumUtil {    public static 
& BaseCodeEnum> E codeOf(Class
enumClass, int code) { E[] enumConstants = enumClass.getEnumConstants(); for (E e : enumConstants) { if (e.getCode() == code) return e; } return null; } }

4. 自定义类型转换器

准备工作做的差不多了,是时候开始编写转换器了。 BaseTypeHandler<T> 一共需要实现4个方法:

  1. void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) 用于定义设置参数时,该如何把Java类型的参数转换为对应的数据库类型
  2. T getNullableResult(ResultSet rs, String columnName) 用于定义通过字段名称获取字段数据时,如何把数据库类型转换为对应的Java类型
  3. T getNullableResult(ResultSet rs, int columnIndex) 用于定义通过字段索引获取字段数据时,如何把数据库类型转换为对应的Java类型
  4. T getNullableResult(CallableStatement cs, int columnIndex) 用定义调用存储过程后,如何把数据库类型转换为对应的Java类型

我是这样实现的:

 
public class CodeEnumTypeHandler
& BaseCodeEnum> extends BaseTypeHandler
{ private Class
type; public CodeEnumTypeHandler(Class
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); } } } }

5. 使用

接下来需要指定哪个类使用我们自己编写转换器进行转换,在MyBatis配置文件中配置如下:

 

搞定! 经测试ComputerState.OPEN被转换为10,ComputerState.UNKNOWN被转换为255,达到了预期的效果。

6. 优化

在第5步时,我们在MyBatis中添加typeHandler用于指定哪些类使用我们自定义的转换器,一旦系统中的枚举类多了起来,MyBatis的配置文件维护起来会变得非常麻烦,也容易出错。如何解决呢? 在Spring中我们可以使用JavaConfig方式来干预SqlSessionFactory的创建过程,来完成动态的转换器指定。 思路

  1. 通过sqlSessionFactory.getConfiguration().getTypeHandlerRegistry()取得类型转换器注册器
  2. 扫描所有实体类,找到实现了BaseCodeEnum接口的枚举类
  3. 将实现了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
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

 
@Componentpublic class ResourcesUtil { private final ResourcePatternResolver resourceResolver; public ResourcesUtil() { this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); } /** * 返回路径下所有class * * @param rootPath 根路径 * @param locationPattern 位置表达式 * @return * @throws IOException */ public List
list(String rootPath, String locationPattern) throws IOException { Resource[] resources = resourceResolver.getResources("classpath*:" + rootPath + locationPattern + "/**/*.class"); List
resourcePaths = new ArrayList<>(); for (Resource resource : resources) { resourcePaths.add(preserveSubpackageName(resource.getURI(), rootPath)); } return resourcePaths; } }

结束了

以上就是我对如何在MyBatis中优雅的使用枚举的探索。如果你还有更优的解决方案,请一定在评论中告知,万分感激。

 

转自:

转载于:https://www.cnblogs.com/zjoch/p/7684013.html

你可能感兴趣的文章
第一次实训作业
查看>>
微信小程序跳转(当我们不知道是普通页面还是tabbar)
查看>>
mac系统下安装和启动nginx
查看>>
linux c 获取文件大小
查看>>
将博客搬至CSDN
查看>>
21. 让指针数组结尾带NULL,使遍历时不依靠计算整个数组大小就可以在结尾遍历结束...
查看>>
阅读作业2李嘉良篇
查看>>
崔博:离开盛大的日子 创业两年回顾
查看>>
sqli-labs(41) and 两php函数的讲解
查看>>
建立动态二维数组
查看>>
selenium之chrome驱动版本
查看>>
sed命令详解
查看>>
Java基于socket的进程间通信 聊天小程序
查看>>
spark集群构建
查看>>
P3932 浮游大陆的68号岛
查看>>
【初赛】数学题错题总结
查看>>
7-第一阶段SCRUM冲刺
查看>>
Kibana4学习<三>
查看>>
使用Ecplise git commit时出现"There are no stages files"
查看>>
php扩展库
查看>>