逻辑删除
删除有两种,一种是逻辑删除,另一种是物理删除
物理删除 是直接删除数据,数据就不再存在
逻辑删除是给数据添加一个标记位deleted
1.1逻辑删除的步骤
1.数据库中表增加一个列deleted
ALTER TABLE `user` ADD COLUMN `deleted` boolean
2.在实体类中加入deleted属性名,添加逻辑删除注解@TableLogic实现逻辑删除
//添加deleted字段,实现逻辑删除,添加@TableLogic
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
3.元对象处理器接口添加deleted的insert默认值
//使用map实现添加操作,这个方法执行
@Override
public void insertFill(MetaObject metaObject) { this.setFieldValByName("deleted",0,metaObject);
}
4.测试逻辑删除
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(1L);
System.out.println(result);
}
5.结果sql显示
==> Preparing: UPDATE user SET deleted=1 WHERE id=? AND deleted=0
==> Parameters: 1(Long)
<== Updates: 1
发现delete的sql语句变为了,更新那个数据的deleted变为1
6.测试逻辑删除后的查询
/**
* 测试 逻辑删除后的查询:
* 不包括被逻辑删除的记录
*/
@Test
public void testLogicDeleteSelect() {
User user = new User();
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
7.结果显示
Preparing: SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0
==> Preparing: SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0
==> Parameters:
<== Columns: id, name, age, email, create_time, update_time, version, deleted
<== Row: 2, Jack, 20, test2@baomidou.com, null, null, null, 0
<== Row: 3, Tom, 28, test3@baomidou.com, null, null, null, 0
<== Row: 4, Sandy, 21, test4@baomidou.com, null, null, null, 0
<== Row: 5, Billie, 24, test5@baomidou.com, null, null, null, 0
<== Row: 1511678850285723650, lucy, 20, 1243qq.com, null, null, null, 0
<== Row: 1512012232764960769, jcl, 120, 1243qq.com, 2022-04-07 18:19:43, 2022-04-07 18:28:26, null, 0
<== Row: 1512027485926064130, 乐观锁数据, 200, 1243qq.com, 2022-04-07 19:20:19, 2022-04-07 19:25:18, 2, 0
<== Row: 1512605723169730561, jccl, 20, 1243qq.com, 2022-04-09 09:38:02, 2022-04-09 09:38:02, 1, 0
<== Total: 8
发现查询语句的sql添加了一个条件where deleted = 0;