8.Mybatis-Plus通用枚举
添加通用枚举的步骤:
- 在枚举类中要添加到数据库中的属性前添加@EnumValue
- 在配置文件中扫描枚举所在的位置
在配置文件中配置枚举位置
mybatis-plus:
type-enums-package: com.example.wx_test.enums
定义枚举类
package com.example.wx_test.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;
@Getter
public enum StatusEnum {
ONTHEJOB(0,"在职"),
QUIT(1,"离职"),
VACATION(2,"休假");
@EnumValue//将注解所标识的属性的值存储在数据库中
private Integer status;
private String statusName;
StatusEnum(Integer status, String statusName) {
this.status = status;
this.statusName = statusName;
}
}
在实体类中添加相应的属性
package com.example.wx_test.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.example.wx_test.enums.StatusEnum;
import lombok.Data;
@TableName("t_employee")
@Data
public class Employee {
private Integer id;
private String name;
private String gender;
private String email;
private String phoneNumber;
@TableField(value = "departmentId")
private Integer departmentId;
private Integer salary;
//枚举类-员工状态
private StatusEnum status;
}
测试类
package com.example.wx_test;
import com.example.wx_test.entity.Employee;
import com.example.wx_test.enums.StatusEnum;
import com.example.wx_test.mapper.EmployeeMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmployeeEnumTest {
@Autowired
private EmployeeMapper employeeMapper;
@Test
public void test(){
Employee employee = new Employee();
employee.setName("王小刀");
employee.setPhoneNumber("12365445611");
employee.setEmail("999@qq.com");
employee.setGender("男");
employee.setDepartmentId(2);
employee.setSalary(9999);
employee.setStatus(StatusEnum.ONTHEJOB);
int result = employeeMapper.insert(employee);
System.out.println(result);
}
}
参考资料:
- https://www.bilibili.com/video/BV12R4y157Be?p=49