MyBatis-Plus通用枚舉自動關(guān)聯(lián)注入的實現(xiàn)
一、通用枚舉
解決了繁瑣的配置,讓 mybatis 優(yōu)雅的使用枚舉屬性!
按我的理解是維護(hù)在內(nèi)存中且不易修改的輕量級字典。目前覺得這個功能的使用場景相對有限,但是如果有用到的話開箱即用也是很棒的。廢話不多說,接下來讓我們看一下它的實際效果吧。
一般搜索用戶信息列表,列如用戶有禁用和啟用兩個狀態(tài)
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private BigInteger id;
private String name;
private String email;
private Integer status;
}
@GetMapping("/findById")
public User findById(){
User user = userMapper.selectById(1);
return user;
}
查詢結(jié)果:

如果前端接收到j(luò)son數(shù)據(jù)后,需要的status字段屬性值,不是1或者2,需要的是禁止或者啟用的中文字,如何解決呢?
二、聲明通用枚舉屬性
public enum StatusEnum implements IEnum<Integer> {
DISABLE(1,"禁用"),
ENABLE(2,"啟用");
private final Integer status; //數(shù)據(jù)庫存儲字段
private final String desc; //返回的顯示描述
StatusEnum(Integer status,String desc){
this.status = status;
this.desc = desc;
}
@Override
public Integer getValue() {
return this.status;
}
@JsonValue
public String getDesc(){
return this.desc;
}
}
實體屬性使用枚舉類型
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private BigInteger id;
private String name;
private String email;
private StatusEnum status;
}
三、配置掃描通用枚舉
#mybatis-plus
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/example/plus/mapper/xml/*.xml
typeEnumsPackage: com.example.plus.enums
加入該配置:
typeEnumsPackage: com.example.plus.enums
測試:

四、注意、注意、注意
1、記得加上@JsonValue注解,序列化時只返回這一個字段的值。
2、配置掃描通用枚舉可能3.0版本以前版本配置不一樣,本列使用的是3.0以上版本
3、通用枚舉無法正確取值,可能會報這樣的錯誤
Caused by: java.lang.IllegalArgumentException: No enum constant
解決方式:
去除 pom.xml中:spring-boot-devtools依賴 ,該插件會導(dǎo)致很多問題
到此這篇關(guān)于MyBatis-Plus通用枚舉自動關(guān)聯(lián)注入的實現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Plus 枚舉自動關(guān)聯(lián)注入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用EasyPOI實現(xiàn)多sheet動態(tài)列導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了如何使用EasyPOI根據(jù)指定時間范圍創(chuàng)建動態(tài)列,以及如何將數(shù)據(jù)組織成符合要求的格式并導(dǎo)出,感興趣的可以了解下2025-03-03

