MyBatisPlus 使用枚举

MyBatisPlus 使用枚举

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

  • 数据库表添加字段sex

  • 创建通用枚举类型

    java 复制代码
    @Getter
    public enum SexEnum {
        MALE(1, "男"),
        FEMALE(2, "女");
    
        @EnumValue //将注解所标识的属性的值存储到数据库中
        private int sex;
        private String sexName;
    
        SexEnum(Integer sex, String sexName) {
            this.sex = sex;
            this.sexName = sexName;
        }
    }
  • User实体类中添加属性sex

    java 复制代码
    public class User {
        private Long id;
        @TableField("username")
        private String name;
        private Integer age;
        private String email;
    
        @TableLogic
        private int isDeleted;  //逻辑删除
    
        private SexEnum sex;
    }
  • 配置扫描通用枚举

    yml 复制代码
    #MyBatis-Plus相关配置
    mybatis-plus:
      #指定mapper文件所在的地址
      mapper-locations: classpath:mapper/*.xml
      configuration:
        #配置日志
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      global-config:
        banner: off
        db-config:
          #配置mp的主键策略为自增
          id-type: auto
          # 设置实体类所对应的表的统一前缀
          table-prefix: t_
      #配置类型别名所对应的包
      type-aliases-package: com.atguigu.mybatisplus.pojo
      # 扫描通用枚举的包
      type-enums-package: com.atguigu.mybatisplus.enums
  • 执行测试方法

    java 复制代码
    @Test
    public void test(){
        User user = new User();
        user.setName("admin");
        user.setAge(33);
        user.setSex(SexEnum.MALE);
        int result = userMapper.insert(user);
        System.out.println("result:"+result);
    }
相关推荐
寒士obj21 小时前
MyBatis-Plus基础篇详解
java·mybatis
陈三一1 天前
MyBatis OGNL 表达式避坑指南
后端·mybatis
funfan05172 天前
在IDEA中DEBUG调试时查看MyBatis-Plus动态生成的SQL语句
sql·intellij-idea·mybatis
JokerSoulClub2 天前
MyBatis-Plus MetaObjectHandler的几个坑(主要是id字段)
mybatis
阿冲Runner2 天前
Lombok的@Builder与Mybatis-Plus配合使用踩坑
java·后端·mybatis
你我约定有三2 天前
MyBatis--缓存详解
spring boot·缓存·mybatis
不羁。。3 天前
【撸靶笔记】第八关:GET - Blind - Boolian Based - Single Quotes
数据库·sql·mybatis
西红柿维生素3 天前
MyBatis SqlCommand+MethodSignature源码探究
mybatis
HeyZoeHey5 天前
Mybatis执行sql流程(一)
java·sql·mybatis
青川入梦5 天前
MyBatis极速通关上篇:Spring Boot环境搭建+用户管理实战
java·开发语言·mybatis