Mybatis-Plus实现逻辑删除
数据库表
create table if not exists tb_student
(
id bigint auto_increment comment '主键id'
primary key,
name varchar(8) not null comment '姓名',
gender int not null comment '性别;1代表男,2代表女',
age int not null comment '年龄',
data_status int default 1 not null comment '数据状态;1代表未被删除,0代表已被删除',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '更新时间',
constraint id
unique (id)
)
comment '学生表';
insert into tb_student (id, name, gender, age, data_status, create_time, update_time)
values (null, '艾伦', 1, 15, 1, now(), now());
StudentEntity
@TableLogic注解有value和delval两个属性,value的值代表数据未被删除,与data_status字段默认的值保持一致,delval的值代表数据已被删除。
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_student")
public class StudentEntity {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField(value = "name")
private String name;
@TableField(value = "gender")
private Integer gender;
@TableField(value = "age")
private Integer age;
@TableLogic(value = "1", delval = "0")
private Integer dataStatus;
@TableField(value = "create_time")
private LocalDateTime createTime;
@TableField(value = "update_time")
private LocalDateTime updateTime;
}
测试
@Autowired
private StudentMapper studentMapper;
@Test
public void test() {
studentMapper.deleteById(1);
}
查看SQL
==> Preparing: UPDATE tb_student SET data_status=0 WHERE id=? AND data_status=1
==> Parameters: 1(Integer)
<== Updates: 1
yml配置文件
在大量的业务需求下,使用@TableLogic注解比较繁琐,而且属性容易写错,推荐使用yml配置文件进行全局设置。
mybatis-plus:
global-config:
db-config:
logic-delete-field: dataStatus #写属性名称,自动映射字段名
logic-not-delete-value: 1 #代表数据未被删除
logic-delete-value: 0 #代表数据已被删除