問題
本文主要給大家介紹的是關于MyBatis使用枚舉的相關內容,我們在編碼過程中,經常會遇到用某個數值來表示某種狀態、類型或者階段的情況,比如有這樣一個枚舉:
1
2
3
4
5
6
7
8
9
10
|
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.EnumTypeHandler
和org.apache.ibatis.type.EnumOrdinalTypeHandler
。
EnumTypeHandler
這是默認的枚舉轉換器,該轉換器將枚舉實例轉換為實例名稱的字符串,即將ComputerState.OPEN
轉換OPEN。
EnumOrdinalTypeHandler
顧名思義這個轉換器將枚舉實例的ordinal屬性作為取值,即ComputerState.OPEN
轉換為0,ComputerState.CLOSE
轉換為1。
使用它的方式是在MyBatis配置文件中定義:
1
2
3
|
<typeHandlers> <typeHandler handler= "org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType= "com.example.entity.enums.ComputerState" /> </typeHandlers> |
以上的兩種轉換器都不能滿足我們的需求,所以看起來要自己編寫一個轉換器了。
方案
MyBatis提供了org.apache.ibatis.type.BaseTypeHandler
類用于我們自己擴展類型轉換器,上面的EnumTypeHandler和EnumOrdinalTypeHandler也都實現了這個接口。
1. 定義接口
我們需要一個接口來確定某部分枚舉類的行為。如下:
1
2
3
|
public interface BaseCodeEnum { int getCode(); } |
該接口只有一個返回編碼的方法,返回值將被存入數據庫。
2. 改造枚舉
就拿上面的ComputerState來實現BaseCodeEnum接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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. 編寫一個轉換工具類
現在我們能順利的將枚舉轉換為某個數值了,還需要一個工具將數值轉換為枚舉實例。
1
2
3
4
5
6
7
8
9
10
11
|
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 ; } } |
4. 自定義類型轉換器
準備工作做的差不多了,是時候開始編寫轉換器了。
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類型
我是這樣實現的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
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); } } } } |
5. 使用
接下來需要指定哪個類使用我們自己編寫轉換器進行轉換,在MyBatis配置文件中配置如下:
1
2
3
|
<typeHandlers> <typeHandler handler= "com.example.typeHandler.CodeEnumTypeHandler" javaType= "com.example.entity.enums.ComputerState" /> </typeHandlers> |
搞定! 經測試ComputerState.OPEN被轉換為10,ComputerState.UNKNOWN
被轉換為255,達到了預期的效果。
6. 優化
在第5步時,我們在MyBatis中添加typeHandler用于指定哪些類使用我們自定義的轉換器,一旦系統中的枚舉類多了起來,MyBatis的配置文件維護起來會變得非常麻煩,也容易出錯。如何解決呢?
在Spring Boot中我們可以干預SqlSessionFactory的創建過程,來完成動態的轉換器指定。
思路
-
通過
sqlSessionFactory.getConfiguration().getTypeHandlerRegistry()
取得類型轉換器注冊器 - 掃描所有實體類,找到實現了BaseCodeEnum接口的枚舉類
- 將實現了BaseCodeEnum的類注冊使用CodeEnumTypeHandler進行轉換。
實現如下:
MyBatisConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
@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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@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中優雅的使用枚舉的探索。如果你還有更優的解決方案,請一定在評論中告知,萬分感激。希望本文的內容對大家的學習或者工作能帶來一定的幫助,謝謝大家對服務器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000010755321