Springboot整合enums类,enums的配置及用法

案例:男,女,后台存储的是1,2,前端展示的是男女

一、创建枚举类

在需要存储数据库的属性上添加@EnumValue注解,在需要前端展示的属性上添加@JsonValue注解;

@JsonValue
可以用在get方法或者属性字段上,一个类只能用一个,当加上@JsonValue注解时,该类的json化结果,只有这个get方法的返回值,而不是这个类的属性键值对.

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.yml里配置

#配置枚举 支持通配符 * 或者 ; 分割
mybatis-plus:
  type-enums-package: com.demo.mybatisplus.constant
  configuration:
    default-enum-type-handler: org.apache.ibatis.type.EnumOrdinalTypeHandler

三、pojo中的sex属性设置为枚举SexEnum;

@ApiModelProperty(value = "性别")
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

前端显示的json值:

[
	{"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 type com.demo.mybatisplus.constant.SexEnum from number 3: index value outside legal index range [0…2];

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
springboot2.7整合knife4j4.3是指在Springboot 2.7版本中使用Knife4j 4.3进行API文档的生成和管理。具体步骤如下: 1.在pom.xml文件中添加Knife4j的依赖: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>4.3.0</version> </dependency> ``` 2.在application.yml文件中进行配置: ``` spring: profiles: active: dev application: name: demo-knife4j-openapi3 servlet: multipart: max-file-size: 10MB max-request-size: 100MB resources: static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 serialization: fail-on-empty-beans: false indent-output: true write-dates-as-timestamps: false write-null-map-values: false write-empty-json-arrays: false write-enums-using-to-string: true http: encoding: charset: UTF-8 enabled: true servlet: session: timeout: 30m datasource: url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 5 min-idle: 5 max-active: 20 test-on-borrow: true validation-query: SELECT 1 FROM DUAL filters: stat,wall,log4j connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 jpa: show-sql: true hibernate: ddl-auto: update naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl server: port: 8080 tomcat: uri-encoding: UTF-8 max-threads: 200 min-spare-threads: 10 max-http-header-size: 1048576 accesslog: enabled: true directory: logs prefix: access_log suffix: .log rotate: true pattern: common knife4j: title: demo-knife4j-openapi3 description: demo-knife4j-openapi3 version: 1.0.0 contact: name: demo-knife4j-openapi3 url: http://localhost:8080/doc.html email: [email protected] license: name: Apache License 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html terms-of-service-url: http://localhost:8080/doc.html host: localhost:8080 packages: com.example.demo ``` 3.在启动上添加@EnableKnife4j注解: ``` @SpringBootApplication @EnableKnife4j public class DemoKnife4jOpenapi3Application { public static void main(String[] args) { SpringApplication.run(DemoKnife4jOpenapi3Application.class, args); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值