Mybatis-Plus 通用枚举

表中的有些字段值是固定的,例如性别(男或女),此时我们可以使用MyBatis-Plus的通用枚举 来实现

数据库表添加字段sex

image-20230513210646108

创建通用枚举类型

package com.example.enums;

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

@Getter
public enum SexEnum {
    MALE(1, "男"),
    FEMALE(0, "女")
    ;

    @EnumValue//标记数据库存的值是code
    private Integer code;
    private String name;

    SexEnum(Integer code, String name) {
        this.code = code;
        this.name = name;
    }
}

配置扫描通用枚举

mybatis-plus:
  configuration:
    # 配置MyBatis日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      # 配置MyBatis-Plus操作表的默认前缀
      table-prefix: t_
      id-type: assign_id
  # 配置扫描通用枚举
  type-enums-package: com.example.enums

测试

@Test
public void testEnum() {
    User user = new User();
    user.setName("enum");
    user.setAge(18);
    user.setSex(SexEnum.MALE);
    //==>  Preparing: INSERT INTO t_user ( id, name, age, sex ) VALUES ( ?, ?, ?, ? )
    //==> Parameters: 1657370519951040514(Long), enum(String), 18(Integer), 1(Integer)
    //<==    Updates: 1
    userMapper.insert(user);
}
posted @ 2023-05-13 22:28  享受生活2023  阅读(62)  评论(0编辑  收藏  举报