学习要求
良好的java基础, 熟悉SpringBoot框架,熟悉Mybatis框架
教学目标
了解并掌握MyBatis-Plus 通用枚举字段实现
视频教程
概念
实际开发中,某些实体对象涉及到状态的变化,一般使用方式有以下2种:
以员工实体举例子
1>使用常量的方式
public class Employee {
public static final int STATUS_NORMAL = 0; //在职
public static final int STATUS_LEAVE = 1; //离职
//员工状态
private int status;
//省略其他属性
}
2>使用枚举方式
//员工状态枚举
@Getter
public enum EmployeeStatus {
NORMAL(0, "在职"), LEAVE(1,"离职");
private int status;
private String label;
private EmployeeStatus(int status, String label){
this.status = status;
this.label = label;
}
}
public class Employee {
//员工状态
private EmployeeStatus status = EmployeeStatus.NORMAL;
//省略其他属性
}
使用常理操作方式与枚举操作方式其实大同小异,枚举赋予状态更多的操作空间,比如每个枚举状态实例,都有方法与属性,灵活性更高。
MyBatis-Plus 枚举字段
还是以员工操作为例子
步骤1:修改员工表,添加status列,类型为int
步骤2:创建EmployeeStatus 枚举类与添加status字段
2种实现方式:
1>实现接口IEnum
@Getter
public enum EmployeeStatus implements IEnum<Integer> {
NORMAL(0, "在职"), LEAVE(1,"离职");
private int status;
private String label;
private EmployeeStatus(int status, String label){
this.status = status;
this.label = label;
}
@Override
public Integer getValue() {
//在表status列中存什么值
return this.status;
}
}
2>使用@EnumValue注解
@Getter
public enum EmployeeStatus{
NORMAL(0, "在职"), LEAVE(1,"离职");
@EnumValue
private int status;
private String label;
private EmployeeStatus(int status, String label){
this.status = status;
this.label = label;
}
}
步骤3:在Employee对象添加status字段
public class Employee {
//员工状态
private EmployeeStatus status = EmployeeStatus.NORMAL;
//省略其他属性
}
步骤4:在application.properties 文件配置操作类
明确指定自定义枚举类所有包路径
mybatis-plus.type-enums-package=com.langfeiyes.mp.enums
步骤5:测试
@Test
public void testSave(){
Employee employee = new Employee();
employee.setAdmin(1);
employee.setAge(18);
employee.setDeptId(1L);
employee.setEmail("zhangsan@163.com");
employee.setName("zhangsan");
employee.setPassword("111");
//执行状态
employee.setStatus(EmployeeStatus.LEAVE);
employeeMapper.insert(employee);
}
执行SQL
==> Preparing: INSERT INTO employee ( id, status, name, password, email, age, admin, dept_id, del, version ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
==> Parameters: 1(Long), 1(Integer), zhangsan(String), 111(String), zhangsan@163.com(String), 18(Integer), 1(Integer), 1(Long), 0(Integer), 0(Integer)
原理
非常简单的逻辑,就是在拼接sql操作时,先解析或者调用getValue方法将枚举对象转换成int类型之后,再进行sql操作。