MyBatis中如何優(yōu)雅的使用枚舉詳解
問(wèn)題
本文主要給大家介紹的是關(guān)于MyBatis使用枚舉的相關(guān)內(nèi)容,我們?cè)诰幋a過(guò)程中,經(jīng)常會(huì)遇到用某個(gè)數(shù)值來(lái)表示某種狀態(tài)、類型或者階段的情況,比如有這樣一個(gè)枚舉:
public enum ComputerState {
OPEN(10), //開啟
CLOSE(11), //關(guān)閉
OFF_LINE(12), //離線
FAULT(200), //故障
UNKNOWN(255); //未知
private int code;
ComputerState(int code) { this.code = code; }
}
通常我們希望將表示狀態(tài)的數(shù)值存入數(shù)據(jù)庫(kù),即ComputerState.OPEN存入數(shù)據(jù)庫(kù)取值為10。
探索
首先,我們先看看MyBatis是否能夠滿足我們的需求。
MyBatis內(nèi)置了兩個(gè)枚舉轉(zhuǎn)換器分別是:org.apache.ibatis.type.EnumTypeHandler和org.apache.ibatis.type.EnumOrdinalTypeHandler。
EnumTypeHandler
這是默認(rèn)的枚舉轉(zhuǎn)換器,該轉(zhuǎn)換器將枚舉實(shí)例轉(zhuǎn)換為實(shí)例名稱的字符串,即將ComputerState.OPEN轉(zhuǎn)換OPEN。
EnumOrdinalTypeHandler
顧名思義這個(gè)轉(zhuǎn)換器將枚舉實(shí)例的ordinal屬性作為取值,即ComputerState.OPEN轉(zhuǎn)換為0,ComputerState.CLOSE轉(zhuǎn)換為1。
使用它的方式是在MyBatis配置文件中定義:
<typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.example.entity.enums.ComputerState"/> </typeHandlers>
以上的兩種轉(zhuǎn)換器都不能滿足我們的需求,所以看起來(lái)要自己編寫一個(gè)轉(zhuǎn)換器了。
方案
MyBatis提供了org.apache.ibatis.type.BaseTypeHandler類用于我們自己擴(kuò)展類型轉(zhuǎn)換器,上面的EnumTypeHandler和EnumOrdinalTypeHandler也都實(shí)現(xiàn)了這個(gè)接口。
1. 定義接口
我們需要一個(gè)接口來(lái)確定某部分枚舉類的行為。如下:
public interface BaseCodeEnum {
int getCode();
}
該接口只有一個(gè)返回編碼的方法,返回值將被存入數(shù)據(jù)庫(kù)。
2. 改造枚舉
就拿上面的ComputerState來(lái)實(shí)現(xiàn)BaseCodeEnum接口:
public enum ComputerState implements BaseCodeEnum{
OPEN(10), //開啟
CLOSE(11), //關(guān)閉
OFF_LINE(12), //離線
FAULT(200), //故障
UNKNOWN(255); //未知
private int code;
ComputerState(int code) { this.code = code; }
@Override
public int getCode() { return this.code; }
}
3. 編寫一個(gè)轉(zhuǎn)換工具類
現(xiàn)在我們能順利的將枚舉轉(zhuǎn)換為某個(gè)數(shù)值了,還需要一個(gè)工具將數(shù)值轉(zhuǎn)換為枚舉實(shí)例。
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. 自定義類型轉(zhuǎn)換器
準(zhǔn)備工作做的差不多了,是時(shí)候開始編寫轉(zhuǎn)換器了。
BaseTypeHandler<T> 一共需要實(shí)現(xiàn)4個(gè)方法:
void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType)
用于定義設(shè)置參數(shù)時(shí),該如何把Java類型的參數(shù)轉(zhuǎn)換為對(duì)應(yīng)的數(shù)據(jù)庫(kù)類型T getNullableResult(ResultSet rs, String columnName)
用于定義通過(guò)字段名稱獲取字段數(shù)據(jù)時(shí),如何把數(shù)據(jù)庫(kù)類型轉(zhuǎn)換為對(duì)應(yīng)的Java類型T getNullableResult(ResultSet rs, int columnIndex)
用于定義通過(guò)字段索引獲取字段數(shù)據(jù)時(shí),如何把數(shù)據(jù)庫(kù)類型轉(zhuǎn)換為對(duì)應(yīng)的Java類型T getNullableResult(CallableStatement cs, int columnIndex)
用定義調(diào)用存儲(chǔ)過(guò)程后,如何把數(shù)據(jù)庫(kù)類型轉(zhuǎn)換為對(duì)應(yīng)的Java類型
我是這樣實(shí)現(xiàn)的:
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. 使用
接下來(lái)需要指定哪個(gè)類使用我們自己編寫轉(zhuǎn)換器進(jìn)行轉(zhuǎn)換,在MyBatis配置文件中配置如下:
<typeHandlers> <typeHandler handler="com.example.typeHandler.CodeEnumTypeHandler" javaType="com.example.entity.enums.ComputerState"/> </typeHandlers>
搞定! 經(jīng)測(cè)試ComputerState.OPEN被轉(zhuǎn)換為10,ComputerState.UNKNOWN被轉(zhuǎn)換為255,達(dá)到了預(yù)期的效果。
6. 優(yōu)化
在第5步時(shí),我們?cè)贛yBatis中添加typeHandler用于指定哪些類使用我們自定義的轉(zhuǎn)換器,一旦系統(tǒng)中的枚舉類多了起來(lái),MyBatis的配置文件維護(hù)起來(lái)會(huì)變得非常麻煩,也容易出錯(cuò)。如何解決呢?
在Spring Boot中我們可以干預(yù)SqlSessionFactory的創(chuàng)建過(guò)程,來(lái)完成動(dòng)態(tài)的轉(zhuǎn)換器指定。
思路
- 通過(guò)
sqlSessionFactory.getConfiguration().getTypeHandlerRegistry()取得類型轉(zhuǎn)換器注冊(cè)器 - 掃描所有實(shí)體類,找到實(shí)現(xiàn)了BaseCodeEnum接口的枚舉類
- 將實(shí)現(xiàn)了BaseCodeEnum的類注冊(cè)使用CodeEnumTypeHandler進(jìn)行轉(zhuǎn)換。
實(shí)現(xiàn)如下:
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);
// 設(shè)置配置文件地址
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factory.setConfigLocation(resolver.getResource(configLocation));
factory.setMapperLocations(resolver.getResources(mapperLocations));
SqlSessionFactory sqlSessionFactory = factory.getObject();
// ----------- 動(dòng)態(tài)加載實(shí)現(xiàn)BaseCodeEnum接口的枚舉,使用CodeEnumTypeHandler轉(zhuǎn)換器
// 取得類型轉(zhuǎn)換注冊(cè)器
TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
// 掃描所有實(shí)體類
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());
// 判斷是否實(shí)現(xiàn)了BaseCodeEnum接口
if (aClass.isEnum() && BaseCodeEnum.class.isAssignableFrom(aClass)) {
// 注冊(cè)
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 位置表達(dá)式
* @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;
}
}
總結(jié)
以上就是我對(duì)如何在MyBatis中優(yōu)雅的使用枚舉的探索。如果你還有更優(yōu)的解決方案,請(qǐng)一定在評(píng)論中告知,萬(wàn)分感激。希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
MyBatisPlus分頁(yè)時(shí)排序的實(shí)現(xiàn)
本文主要介紹了MyBatisPlus分頁(yè)時(shí)排序的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Spring boot中使用Spring-data-jpa方便快捷的訪問(wèn)數(shù)據(jù)庫(kù)(推薦)
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規(guī)范的基礎(chǔ)上封裝的一套JPA應(yīng)用框架,可使開發(fā)者用極簡(jiǎn)的代碼即可實(shí)現(xiàn)對(duì)數(shù)據(jù)的訪問(wèn)和操作。這篇文章主要介紹了Spring-boot中使用Spring-data-jpa方便快捷的訪問(wèn)數(shù)據(jù)庫(kù),需要的朋友可以參考下2018-05-05
Spring通過(guò)配置文件管理Bean對(duì)象的方法
這篇文章主要介紹了Spring通過(guò)配置文件管理Bean對(duì)象的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件(最新推薦)
這篇文章主要介紹了IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-01-01
詳解DES加密算法的原理與Java實(shí)現(xiàn)
DES 加密,是對(duì)稱加密。對(duì)稱加密,顧名思義,加密和解密的運(yùn)算全都是使用的同樣的秘鑰。這篇文章主要為大家講講DES加密算法的原理與Java實(shí)現(xiàn),需要的可以參考一下2022-10-10
解決Mybatis?mappe同時(shí)傳遞?List?和其他參數(shù)報(bào)錯(cuò)的問(wèn)題
在使用MyBatis時(shí),如果需要傳遞多個(gè)參數(shù)到SQL中,可以遇到參數(shù)綁定問(wèn)題,解決方法包括使用@Param注解和修改mapper.xml配置,感興趣的朋友跟隨小編一起看看吧2024-09-09
Java異常區(qū)分和處理的一些經(jīng)驗(yàn)分享
這篇文章介紹了Java異常區(qū)分和處理的一些經(jīng)驗(yàn)分享,主要是異常選擇和使用中的一些誤區(qū)總結(jié)與歸納,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
使用java實(shí)現(xiàn)手機(jī)短信驗(yàn)證全過(guò)程
這篇文章主要介紹了使用java實(shí)現(xiàn)手機(jī)短信驗(yàn)證全過(guò)程,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04

