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);
    }
相关推荐
41541114 小时前
MyBatis-Plus + PostGIS 实战(四):GeoJSON 序列化与前端地图对接,全局 WKT + 局部 GeoJSON,两种格式优雅共存
java·mybatis·postgis·geojson
Full Stack Developme17 小时前
MyBatis-Plus(MP)AST 抽象语法树 设计原理
java·tomcat·mybatis
han_hanker2 天前
mybatis-plus service层拥有的方法
mybatis
ruleslol3 天前
Mybatis11-不同的数据库连接池的配置
数据库·mybatis
干到60岁退休的码农3 天前
整合Mybatis-Plus分页插件并实现分页api方法
java·mybatis
han_hanker3 天前
mybatis-plus 常用方法
java·tomcat·mybatis
李少兄3 天前
MyBatis、MyBatis-Plus 与全自动 ORM 的本质区别
mybatis
干到60岁退休的码农3 天前
SpringBoot整合Mybatis-plus
spring boot·后端·mybatis
4154113 天前
MyBatis-Plus + PostGIS 实战(二):空间查询与空间索引
java·mybatis·gis·postgis
AgCl233 天前
JavaWeb个人笔记01--Maven到MyBatis
笔记·maven·mybatis