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);
    }
相关推荐
从此以后自律2 天前
MyBatis-Plus 内置分页、PageHelper 自定义分页
mybatis
4154112 天前
MyBatis-Plus + PostGIS 实战(1.1):Geometry 字段在 Swagger 中的优雅展示
java·mybatis·postgis
4154113 天前
MyBatis-Plus + PostGIS 实战一(基础篇)
java·mybatis·postgis
Wang's Blog3 天前
Java框架快速入门:深入MyBatis-Plus高级DML操作(ID策略·逻辑删除·乐观锁)
java·数据库·mybatis
丑八怪大丑4 天前
MyBatis
mybatis
从此以后自律4 天前
MyBatis 与 MyBatis-Plus 完整对比讲解
mybatis
SQL-First布道者4 天前
Spring JDBC Ultra 十边型战士
java·spring boot·后端·mysql·spring·mybatis
han_hanker5 天前
sql语法 MyBatis <foreach> 标签详解
windows·sql·mybatis
ByWalker_6 天前
web应用技术—MyBatis入门
java·数据库·mybatis·lombok
ylscode7 天前
Cloudflare Workers Cache 深度解析:边缘缓存如何重塑无服务器性能边界
java·spring·mybatis