【10】SpringBoot4 MyBatisPlus 枚举类型(enum)

SpringBoot4 MyBatisPlus 枚举类型(enum)

前言

SpringBoot 版本:4.0.8

JDK 版本:21.0.11

IDEA 开发工具版本:2026.2

MySQL 数据库版本:8.4.11.LTS

sql 复制代码
 CREATE TABLE tb_client (
    id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',
    client_id BIGINT NOT NULL COMMENT 'ID编号',
    user_no VARCHAR(30) COMMENT '账号',
    user_password VARCHAR(60) COMMENT '密码',
    nick_name VARCHAR(30) COMMENT '昵称',
    real_name VARCHAR(30) COMMENT '真实姓名',
    status TINYINT NOT NULL DEFAULT 0 COMMENT '状态(0:可用,1:禁用)',
    info JSON COMMENT '扩展信息',
    created_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    upated_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间'
) COMMENT = '客户端信息表';


INSERT INTO tb_client
(client_id, user_no, user_password, nick_name, real_name, info)
VALUES
(100001, 'zhangsan', '123456', '张三', '张三', '{"age": 25, "gender": "male", "city": "上海"}'),
(100002, 'lisi', '123456', '李四', '李四', '{"age": 28, "gender": "male", "city": "北京"}'),
(100003, 'wangwu', '123456', '王五', '王五', '{"age": 30, "gender": "male", "city": "深圳"}');

创建工程

参考《SpringBoot4 MyBatisPlus 代码自动生成》,

使用代码自动生成如下:

用户状态(status)是 Integer 类型,建议修改为 枚举 类型.

pom.xml

xml 复制代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.0.8</version>
    <relativePath/>
  </parent>

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.junjiu.mybatisplus</groupId>
  <artifactId>springboot4-mybatisplus</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot4-mybatisplus</name>
  <url>http://maven.apache.org</url>


  <properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <mybatis-plus.version>3.5.17</mybatis-plus.version>
    <fastjson2.version>2.0.65</fastjson2.version>
    <druid.version>1.2.28</druid.version>

  </properties>


  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>

    <!-- ======================================= -->
    <!-- MyBatis Plus -->
    <!-- ======================================= -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-spring-boot4-starter</artifactId>
      <version>${mybatis-plus.version}</version>
    </dependency>

    <!-- ======================================= -->
    <!-- MySQL -->
    <!-- Spring Boot 4.0.8 BOM 管理版本:9.7.0 -->
    <!-- ======================================= -->
    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <scope>runtime</scope>
    </dependency>

    <!-- ======================================= -->
    <!-- Druid -->
    <!-- ======================================= -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-4-starter</artifactId>
      <version>1.2.28</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <scope>annotationProcessor</scope>
    </dependency>

    <dependency>
      <groupId>com.alibaba.fastjson2</groupId>
      <artifactId>fastjson2</artifactId>
      <version>${fastjson2.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

  </dependencies>

</project>

application.yml

yaml 复制代码
spring:
  application:
    name: springboot3-mybatisplus-pro
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.88.101:3305/testdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
    username: admin
    password: Qwer@1314

    druid:
      # 初始化连接数
      initial-size: 5
      # 最小空闲连接数
      min-idle: 5
      # 最大连接数
      max-active: 20
      # 获取连接最大等待时间
      max-wait: 60000
      # 定期检测空闲连接
      time-between-eviction-runs-millis: 60000
      # 最小空闲时间
      min-evictable-idle-time-millis: 300000
      # 连接有效性检测
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # SQL 统计
      filter:
        stat:
          enabled: true
          log-slow-sql: true
          slow-sql-millis: 2000
        wall:
          enabled: true

mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml
  type-aliases-package: com.junjiu.**.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
  global-config:
    banner: false
    db-config:
      id-type: assign_id
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0

创建枚举类(UserStatusEnum)

java 复制代码
package com.junjiu.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

/**
 * 用户状态枚举
 *
 */
@Getter
public enum UserStatusEnum {

    NORMAL(0, "正常"),
    FREEZE(1, "冻结");

    @EnumValue
    private Integer code;
    private String message;

    UserStatusEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

}

调整实体类(TbClient)

将用户状态(status)的类型由 Integer 修改为枚举类型(UserStatusEnum)

创建测试类

EnumTest

java 复制代码
package com.junjiu.mybatisplus;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.junjiu.mybatisplus.entity.TbClient;
import com.junjiu.mybatisplus.service.ITbClientService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class EnumTest {

    @Autowired
    ITbClientService clientService;

    @Test
    public void testSelect() {

        TbClient client = clientService.getById(1);
        System.out.println(JSON.toJSONString(client, JSONWriter.Feature.PrettyFormat));
    }
}

运行结果如下:

若想让结果显示为 code 或者 message ,则需要在 enum 上面添加 @JSONField 注解。

例如:

java 复制代码
    @JSONField
    private String message;

再次运行测试结果,如下:

相关推荐
mmsx6 小时前
耳切法切带洞多边形:论文能跑通,真实数据为什么崩
android·kotlin
洞见前行6 小时前
你的 Activity 关了,为什么还活着?Android 内存泄漏从发现、定位到线上治理
android·性能优化·leakcanary
Kapaseker8 小时前
Kotlin 又要加语法糖了:这次轮到 if-else
android·kotlin
恋猫de小郭9 小时前
Flutter 3.50 & Dart 3.14 发布,快来看看有什么更新吧
android·前端·flutter
Starry-sky(jing)1 天前
Vidda ADB 开启:R Pro 65 找不到开发者选项的处理与连接验收
android·adb·远程控制·电视·vidda
雨白1 天前
从原理到实践:使用 Kotlin KSP 仿写 ButterKnifeLite
android·kotlin
疯华整猫1 天前
把二十七个 init 从首帧前面搬走:用 Trae 把启动优化钉进 CI
android·性能优化·ai编程
传奇开心果1 天前
【探秘 Jetpack Compose 框架深水区】 第8课:rememberSaveable 的边界在哪里?——Bundle、Saver 与什么值得跨进程存活
android·kotlin