MyBatisPlus(十七)通用枚举

说明

MyBatisPlus 优雅地使用枚举类型。

声明通用枚举属性

使用 @EnumValue 注解枚举属性

java 复制代码
package com.example.web.enumeration;

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.AllArgsConstructor;

/**
 * 性别枚举
 */
@AllArgsConstructor
public enum GenderEnum {

    UNKNOWN(0, "未知"),
    MALE(1, "男"),
    FEMALE(2, "女");

    @EnumValue // 标记数据库存的值是 code
    @JsonValue // 序列化枚举值为 接口出参;接口入参(RequestBody),反序列化为枚举值
    private final int code;

    private final String description;

}

实体属性使用枚举类型

java 复制代码
package com.example.web.entity;

import com.example.web.enumeration.GenderEnum;
import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private Integer deleted;
    private GenderEnum gender;
}

数据库关系模式

测试

新增测试

代码

java 复制代码
    /**
     * 插入用户(男性)
     */
    @Test
    public void insertMale() {
        User user = new User();
        user.setId(10L);
        user.setName("钱一");
        user.setAge(26);
        user.setEmail("qianyi@example.com");
        user.setGender(GenderEnum.MALE);

        mapper.insert(user);
    }


    /**
     * 插入用户(女性)
     */
    @Test
    public void insertFemale() {
        User user = new User();
        user.setId(11L);
        user.setName("钱二");
        user.setAge(26);
        user.setEmail("qianer@example.com");
        user.setGender(GenderEnum.FEMALE);

        mapper.insert(user);
    }


    /**
     * 插入用户(未填写性别)
     */
    @Test
    public void insertUnknown() {
        User user = new User();
        user.setId(12L);
        user.setName("钱三");
        user.setAge(26);
        user.setEmail("qiansan@example.com");

        mapper.insert(user);
    }

结果

插入用户(男性):

插入用户(女性):

插入用户(未填写性别):

数据库中的数据:

查询测试

java 复制代码
    @Test
    public void selectById() {
        User user = mapper.selectById(10);
        log.info("user:{}", user);
    }

序列化枚举值为接口参数值

  1. 序列化枚举值为接口出参
  2. 接口入参(RequestBody),反序列化为枚举值。

这两种实现,都是通过 @JsonValue 注解实现的。

测试:序列化枚举值为接口出参

java 复制代码
    @GetMapping
    public List<User> selectAll() {
        return userService.list();
    }

测试:接口入参(RequestBody),反序列化为枚举值

java 复制代码
    @PostMapping
    public void addUser(@Valid @RequestBody User param) {
        log.info("新增用户:param={}", param);
    }

服务器接收到的数据,打印log

新增用户:param=User(id=70, name=小明, age=20, email=xiaoming@qq.com, deleted=0, gender=MALE)

Query参数,使用枚举(待完善,暂不推荐)

当前方法,使用枚举的名字作为请求参数。

更好的办法是,使用枚举值,和Body参数以及数据库中定义保持一致。

配置代码

java 复制代码
package com.example.core.config;

import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 通过ApplicationConversionService向应用中注入Converter
        ApplicationConversionService.configure(registry);
    }
}

接口测试

java 复制代码
    @GetMapping("selectByUser")
    public List<User> selectByUser(User query) {
        log.info("查询用户:query={}", query);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(query.getGender()), User::getGender, query.getGender());
        return userService.list(wrapper);
    }

Log日志:

查询用户:query=User(id=null, name=null, age=null, email=null, deleted=null, gender=MALE)

相关推荐
程序员阿卢1 小时前
01-基于springboot框架调用ollama下的模型完成基本功能
spring boot·后端·ollama·通义千问模型qwen
烧饼Fighting1 小时前
Jenkins自动化编译部署Spring Boot项目
spring boot·自动化·jenkins
闪电悠米1 小时前
黑马点评-Redis 消息队列-01_why_redis_mq
java·数据库·spring boot·redis·缓存·junit·消息队列
我登哥MVP2 小时前
Spring Boot 从“会用”到“精通”:内容协商原理
java·spring boot·后端·spring·java-ee·maven·lua
Flittly2 小时前
【AgentScope Java新手村系列】(1)框架简介与环境搭建
java·spring boot·笔记·spring·ai
星辰徐哥10 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥10 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约10 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee11 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐11 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统