mybatis-plus enum實(shí)現(xiàn)枚舉類型自動(dòng)轉(zhuǎn)換
mybatis-plus實(shí)現(xiàn)了對“實(shí)體類指定了枚舉類型,想查詢時(shí)返回的是枚舉值而非value值”,“插入數(shù)據(jù)時(shí),實(shí)體賦值的是枚舉類型,想入庫時(shí)插入對應(yīng)的value值”,“不想寫其他的handler處理程序,希望能夠自動(dòng)處理”。
mybatis-plus對于上述的訴求都可以滿足,簡單的處理方案是:
* 1、實(shí)現(xiàn) IEnum of T
* 2、注解 @EnumValue,不用實(shí)現(xiàn) IEnum of T
具體的官方文檔為 https://mp.baomidou.com/guide/enum.html
定義一個(gè)簡單實(shí)體
先定義一個(gè)示例實(shí)體類,我們在實(shí)體Demo中用到了DemoStatusEnum
/** * 實(shí)體類 */ @Data @TableName("demo") public class Demo extends Model<Demo> { @TableField("status") private DemoStatusEnum status; }
DemoStatusEnum枚舉定義
我們采用了官方提到的兩種方式的第一種:即實(shí)現(xiàn)IEnum<T>
/** * 支持枚舉值的兩種方式 * 1、實(shí)現(xiàn) IEnum of T * 2、注解 @EnumValue,不用實(shí)現(xiàn) IEnum of T */ @Getter public enum DemoStatusEnum implements IEnum<Integer> { DEFAULT(0, "default"), NORMAL(1, "normal"), LOCKED(2, "locked"); DemoStatusEnum(Integer value, String desc) { this.value = value; this.desc = desc; } private Integer value; private String desc; @Override public Integer getValue() { return this.value; } }
如果不想繼承IEnum<T>,
可以通過第二種方式,就是增加一個(gè)注解的方式@EnumValue
@EnumValue private Integer value; @JsonValue private String desc;
自動(dòng)轉(zhuǎn)換實(shí)現(xiàn):
配置了Enums枚舉,實(shí)體中設(shè)置了枚舉類型,那么mybatis-plus如何轉(zhuǎn)換的呢?重點(diǎn)是看這里
mybatis-plus: global-config: db-config: logic-not-delete-value: 0 #邏輯未刪除值為數(shù)據(jù)庫主鍵 logic-delete-value: id #邏輯刪除值是個(gè)d # logic-delete-value: "now()" #邏輯刪除值是個(gè)db獲取時(shí)間的函數(shù) # logic-not-delete-value: "null" #邏輯未刪除值為字符串 "null" # logic-not-delete-value: "1753-01-01 00:00:00" configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 如果是放在src/main/java目錄下 classpath:/com/*/*/mapper/*Mapper.xml # 如果是放在resource目錄 classpath:/mapper/**.xml default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler # 如果是放在src/main/java目錄下 classpath:/com/*/*/mapper/*Mapper.xml # 如果是放在resource目錄 classpath:/mapper/**.xml # 支持統(tǒng)配符 * 或者 ; 分割 typeEnumsPackage: com.fii.gxback.eam.domain.enums
通過上述的配置后,就可以了。那么,接下來我們重點(diǎn)分析一下type-enums-package
按照官方文檔說明:
枚舉類 掃描路徑,如果配置了該屬性,會(huì)將路徑下的枚舉類進(jìn)行注入,讓實(shí)體類字段能夠簡單快捷的使用枚舉屬性
通過扒源碼發(fā)現(xiàn),其實(shí)是幫我們實(shí)現(xiàn)了對應(yīng)的 typehandler(com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler
)
其中,isMpEnums
中,判定整合兩種方式的判定,即 IEnum.class
、EnumValue.class
/** * 判斷是否為MP枚舉處理 * * @param clazz class * @return 是否為MP枚舉處理 * @since 3.3.1 */ public static boolean isMpEnums(Class<?> clazz) { return clazz != null && clazz.isEnum() && (IEnum.class.isAssignableFrom(clazz) || findEnumValueFieldName(clazz).isPresent()); } /** * 查找標(biāo)記標(biāo)記EnumValue字段 * * @param clazz class * @return EnumValue字段 * @since 3.3.1 */ public static Optional<String> findEnumValueFieldName(Class<?> clazz) { if (clazz != null && clazz.isEnum()) { String className = clazz.getName(); return Optional.ofNullable(CollectionUtils.computeIfAbsent(TABLE_METHOD_OF_ENUM_TYPES, className, key -> { Optional<Field> optional = Arrays.stream(clazz.getDeclaredFields()) // 過濾包含注解@EnumValue的字段 .filter(field -> field.isAnnotationPresent(EnumValue.class)) .findFirst(); return optional.map(Field::getName).orElse(null); })); } return Optional.empty(); }
然后,在com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean#buildSqlSessionFactory
中,
// 取得類型轉(zhuǎn)換注冊器 TypeHandlerRegistry typeHandlerRegistry = targetConfiguration.getTypeHandlerRegistry(); classes.stream() .filter(Class::isEnum) .filter(MybatisEnumTypeHandler::isMpEnums) .forEach(cls -> typeHandlerRegistry.register(cls, MybatisEnumTypeHandler.class));
驗(yàn)證邏輯
controller:
@RequestMapping("/{id}") public Demo get(@PathVariable("id") Long id) { return demoService.getById(id); }
輸出:
"status": "DEFAULT"
可以看到,status最終輸出的不是魔術(shù)數(shù)字0,而是枚舉值default。
其實(shí),跟一下代碼,可以發(fā)現(xiàn),跟我們自己手寫一個(gè)typeHandler沒區(qū)別,這里最終獲取轉(zhuǎn)換值時(shí),調(diào)用了com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler#getNullableResult(java.sql.ResultSet, int)
,此時(shí)已經(jīng)拿到了枚舉值的具體類是什么了。接下來就是調(diào)用valueOf去獲取對應(yīng)的枚舉值即可。
附源碼:
package org.apache.ibatis.type; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> { private final Class<E> type; private final E[] enums; public EnumOrdinalTypeHandler(Class<E> type) { if (type == null) { throw new IllegalArgumentException("Type argument cannot be null"); } else { this.type = type; this.enums = (Enum[])type.getEnumConstants(); if (this.enums == null) { throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type."); } } } public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, parameter.ordinal()); } public E getNullableResult(ResultSet rs, String columnName) throws SQLException { int ordinal = rs.getInt(columnName); return ordinal == 0 && rs.wasNull() ? null : this.toOrdinalEnum(ordinal); } public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException { int ordinal = rs.getInt(columnIndex); return ordinal == 0 && rs.wasNull() ? null : this.toOrdinalEnum(ordinal); } public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { int ordinal = cs.getInt(columnIndex); return ordinal == 0 && cs.wasNull() ? null : this.toOrdinalEnum(ordinal); } private E toOrdinalEnum(int ordinal) { try { return this.enums[ordinal]; } catch (Exception var3) { throw new IllegalArgumentException("Cannot convert " + ordinal + " to " + this.type.getSimpleName() + " by ordinal value.", var3); } } }
到此這篇關(guān)于mybatis-plus enum實(shí)現(xiàn)枚舉類型自動(dòng)轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)mybatis-plus 枚舉自動(dòng)轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)Runnable接口適合資源的共享
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)Runnable接口適合資源的共享,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07定時(shí)任務(wù)注解@Scheduled不生效問題及解決
這篇文章主要介紹了定時(shí)任務(wù)注解@Scheduled不生效問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06eclipse報(bào)錯(cuò) eclipse啟動(dòng)報(bào)錯(cuò)解決方法
本文將介紹eclipse啟動(dòng)報(bào)錯(cuò)解決方法,需要了解的朋友可以參考下2012-11-11SSH框架網(wǎng)上商城項(xiàng)目第9戰(zhàn)之添加和更新商品類別功能實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了SSH框架網(wǎng)上商城項(xiàng)目第9戰(zhàn)之添加和更新商品類別功能實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2016-06-06Spring @Bean注解的使用場景與案例實(shí)現(xiàn)
隨著SpringBoot的流行,我們現(xiàn)在更多采用基于注解式的配置從而替換掉了基于XML的配置,所以本篇文章我們主要探討基于注解的@Bean以及和其他注解的使用2023-03-03SpringCloud OpenFeign基本介紹與實(shí)現(xiàn)示例
OpenFeign源于Netflix的Feign,是http通信的客戶端。屏蔽了網(wǎng)絡(luò)通信的細(xì)節(jié),直接面向接口的方式開發(fā),讓開發(fā)者感知不到網(wǎng)絡(luò)通信細(xì)節(jié)。所有遠(yuǎn)程調(diào)用,都像調(diào)用本地方法一樣完成2023-02-02淺談HTTP使用BASIC認(rèn)證的原理及實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄獪\談HTTP使用BASIC認(rèn)證的原理及實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-11-11