詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理
前言:
在開發(fā)中,我們經常會用到諸如:性別(男/女)、審核狀態(tài)(未審核/審核中/已審核)之類的數(shù)據(jù),通常會在數(shù)據(jù)庫中使用一個數(shù)字類型的字段來標識,比如:性別,用1來表示男,2來表示女,而在代碼中一般會定義成enum類型或靜態(tài)常量來避免在業(yè)務代碼中出現(xiàn)“0/1”這種魔法值,但是在數(shù)據(jù)庫存儲及前后端交互的時候,就需要進行轉化;無論是在SQL、前端還是后臺轉化,都需要寫相應的代碼,無形中增加了開發(fā)工作量;mybatis-plus實現(xiàn)了對該問題的處理,能夠讓我們在查詢數(shù)據(jù)庫時,直接能夠返回字段標識的意思。配置如下:
第一步:
創(chuàng)建枚舉類,在需要存儲數(shù)據(jù)庫的屬性上添加@EnumValue注解,在需要前端展示的屬性上添加@JsonValue注解;
package com.demo.mybatisplus.constant; import com.baomidou.mybatisplus.annotation.EnumValue; import com.fasterxml.jackson.annotation.JsonValue; public enum SexEnum { MAN(1, "男"), WOMAN(2, "女"); @EnumValue private Integer key; @JsonValue private String display; SexEnum(Integer key, String display) { this.key = key; this.display = display; } public Integer getKey() { return key; } public String getDisplay() { return display; } }
第二步:
application.properties文件里添加配置,定義掃描枚舉類的包路徑;
#配置枚舉 支持通配符 * 或者 ; 分割 mybatis-plus.type-enums-package=com.demo.mybatisplus.constant #mybatis-plus.configuration.default-enum-type-handler=org.apache.ibatis.type.EnumOrdinalTypeHandler
第三步:
pojo中的sex屬性設置為枚舉SexEnum;
@ApiModelProperty(value = "性別") @TableField("sex") private SexEnum sex;
測試:
@Test public void insert() { UserInfo userInfo = new UserInfo(); userInfo.setAge(22); userInfo.setName("李四"); userInfo.setSex(SexEnum.WOMAN); userInfoMapper.insert(userInfo); System.out.println(userInfo); }
數(shù)據(jù)庫保存的值:
ID | NAME | AGE | SEX |
---|---|---|---|
1 | 張三 | 11 | 1 |
2 | 李四 | 22 | 2 |
3 | 王五 | 33 | 1 |
前端顯示的值:
[ {"id":"1","name":"張三","age":11,"sex":"男"}, {"id":"2","name":"李四","age":22,"sex":"女"}, {"id":"3","name":"王五","age":33,"sex":"男"} ]
注意事項:
@EnumValue標記的枚舉類屬性的類型要和數(shù)據(jù)庫字段的類型對應,否則在查詢數(shù)據(jù)的時候無法轉化為枚舉類型,并顯示為null;
如果查詢的時候,數(shù)據(jù)庫字段的值匹配不到枚舉,程序運行時并不會報錯,而是顯示為null;
在保存的時候,前端需要傳遞@JsonValue標記的枚舉類屬性的值,即"男/女";因為Enum的屬性ordinal(int),在測試過程中,傳枚舉值在枚舉類中的定義順序(或者稱為索引,順序從0開始),也可以轉換為相應的枚舉值,比如:上面定義的SexEnum枚舉,前端傳0或者"0",會轉換成MAN,傳1或者"1"會轉換成WOMAN;傳其他值會報異常:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type com.demo.mybatisplus.constant.SexEnum from String "3": not one of the values accepted for Enum class: [女, 男]或com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of typecom.demo.mybatisplus.constant.SexEnum from number 3: index value outside legal index range [0..2];
到此這篇關于詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理的文章就介紹到這了,更多相關mybatis-plus EnumValue枚舉內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java連接 JDBC基礎知識(操作數(shù)據(jù)庫:增刪改查)
這篇文章主要介紹了Java連接 JDBC基礎知識,包括操作數(shù)據(jù)庫之增刪改查操作,需要的朋友可以參考下2021-04-04java 注解annotation的使用以及反射如何獲取注解
這篇文章主要介紹了java 注解annotation的使用以及反射如何獲取注解的相關資料,需要的朋友可以參考下2017-01-01