您好,登录后才能下订单哦!
今天就跟大家聊聊有关怎么在mybatis-plus中利用@EnumValue注解的方式对枚举进行处理,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
创建枚举类,在需要存储数据库的属性上添加@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);
 }数据库保存的值:
| 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标记的枚举类属性的类型要和数据库字段的类型对应,否则在查询数据的时候无法转化为枚举类型,并显示为null;
如果查询的时候,数据库字段的值匹配不到枚举,程序运行时并不会报错,而是显示为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注解的方式对枚举进行处理有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。