文章目录
一、基本删除操作
1、删除单个id
@Test
public void testDeleteById(){
userMapper.deleteById(1559476030644174853L);
}
2、批量删除id
@Test
public void testDeleteBatchIds(){
userMapper.deleteBatchIds(Arrays.asList(1559476030644174853L,1559476030644174854L));
}
3、通过map条件删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","酷小亚,想要进大厂!");
map.put("age",18);
userMapper.deleteByMap(map);
}
二、(1)【新版】逻辑删除操作
首先要明白两个概念
物理删除:从数据库中直接删除
逻辑删除:在数据库中没有删除,而是通过一个变量来让他失效。
类似:回收站!
首先:导入依赖版本(3.4.0及其以上)
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
1、在数据表中增加一个deleted字段
2、实体类中增加属性
//逻辑删除组件
@TableLogic
private Integer deleted;
3、配置组件
@EnableTransactionManagement
@MapperScan("com.jin.mapper")
@Configuration //配置类
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
/* //添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
*/
//逻辑删除组件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
# 配置逻辑删除
mybatis-plus:
global-config:
db-config:
# 删除状态为1
logic-delete-value: 1
# 没有删除状态为0
logic-not-delete-value: 0
4、测试代码
@Test
public void testDeleteById(){
userMapper.deleteById(66L);
}
记录依旧存在数据库中,但是值已经发生了变化!
再查询逻辑删除后的此字段时,则显示为空!
@Test
void testSelectd(){
User user = userMapper.selectById(66L);
System.out.println(user);
}
二、(2)【旧版】逻辑删除操作
导入旧版本依赖
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
配置组件有所改变
@EnableTransactionManagement
@MapperScan("com.jin.mapper")
@Configuration //配置类
public class MyBatisPlusConfig {
// 逻辑删除组件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
其余不变
总结
- 逻辑删除的字段,查询时显示为空,不存在!其实数据库中仍显示存在该数据。类似
回收站
- 逻辑删除好处:管理员可以查看被删除的记录,
防止数据的丢失
。