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);
    }
相关推荐
sensenlin911 天前
Mybatis中SQL全大写或全小写影响执行性能吗
数据库·sql·mybatis
BXCQ_xuan1 天前
软件工程实践四:MyBatis-Plus 教程(连接、分页、查询)
spring boot·mysql·json·mybatis
wuyunhang1234561 天前
Redis----缓存策略和注意事项
redis·缓存·mybatis
lunz_fly19921 天前
【源码解读之 Mybatis】【基础篇】-- 第2篇:配置系统深度解析
mybatis
森林-1 天前
MyBatis 从入门到精通(第一篇)—— 框架基础与环境搭建
java·tomcat·mybatis
森林-2 天前
MyBatis 从入门到精通(第三篇)—— 动态 SQL、关联查询与查询缓存
sql·缓存·mybatis
java干货2 天前
MyBatis 的“魔法”:Mapper 接口是如何找到并执行 SQL 的?
数据库·sql·mybatis
嬉牛2 天前
项目日志输出配置总结(多数据源MyBatis+Logback)
mybatis·logback
哈喽姥爷3 天前
Spring Boot--yml配置信息书写和获取
java·数据库·spring boot·mybatis
奔跑你个Run4 天前
mybatis plus 使用wrapper输出SQL
mybatis