14、Mybatis-Plus之通用枚举

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

1、数据库表添加字段sex

image-20230711112406818

2、创建通用枚举类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.jw.cloud.mybatisplus.enums;
import com.baomidou.mybatisplus.annotation.IEnum;
/**
* @author JoyWu
*/

public enum SexEnum implements IEnum<Integer> {
/**
* 性别枚举
*/
MAN(1,"男"),
WOMAN(2,"女");
public int value;
public String sex;

SexEnum(Integer value, String sex) {
this.value = value;
this.sex = sex;
}

@Override
public Integer getValue() {
return value;
}

public int getValues() {
return value;
}

public String getSex() {
return sex;
}
public static SexEnum getInstance(int sex) {
for (SexEnum jobEnum : values()) {
if (jobEnum.getValues() == sex) {
return jobEnum;
}
}
return null;
}
}

1
2
```

package com.jw.cloud.mybatisplus.enums;

import com.baomidou.mybatisplus.annotation.IEnum;

/**

  • @author JoyWu
    */

public enum JobEnum implements IEnum {
/**
* 医生
*/
Doctor(1, “医生”,”WWW”),
Teacher(2, “老师”,”qqqq”),
Programmer(3, “程序员”,”pppp”),
Driver(4, “司机”,”oooo”);
public int jobId;
public String jobName;
public String des;

JobEnum(int jobId, String jobName, String des) {
    this.jobId = jobId;
    this.jobName = jobName;
    this.des = des;
}


public int getJobId() {
    return jobId;
}

public String getJobName() {
    return jobName;
}

public static JobEnum getJobEnum(int JobId) {
    for (JobEnum jobEnum : values()) {
        if (jobEnum.getJobId() == JobId) {
            return jobEnum;
        }
    }
    return null;
}

@Override
public Integer getValue() {
    return this.jobId;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

## 3、配置扫描通用枚举

```yaml
mybatis-plus:
configuration:
# 配置MyBatis日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 配置MyBatis-Plus操作表的默认前缀
table-prefix: t_
# 配置MyBatis-Plus的主键策略
id-type: auto
# 配置扫描通用枚举
typeEnumsPackage: com.jw.cloud.mybatisplus.enums

4、测试

1
2
3
4
5
6
7
8
9
10
11
@Test
public void testSexEnum(){
User user = new User();
user.setName("Enum");
user.setAge(20);
//设置性别信息为枚举项,会将@EnumValue注解所标识的属性值存储到数据库
user.setSex(SexEnum.MALE);
//INSERT INTO t_user ( username, age, sex ) VALUES ( ?, ?, ? )
//Parameters: Enum(String), 20(Integer), 1(Integer)
userMapper.insert(user);
}