MyBatis-Plus逻辑删除

Posted yangzhlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis-Plus逻辑删除相关的知识,希望对你有一定的参考价值。

MyBatis-Plus逻辑删除指,在数据库中删除数据时,并没有真正的删除,而是更改指定字段的值,这个字段的值可以为0或1,0代表未删除,1代表已删除,所以delete操作实际上是update操作,查询操作也是要加where条件过滤掉已删除的数据

MyBatis-Plus配置逻辑删除:

1.#MyBatisPlus全局配置
global-config:
  db-config:
 
    #全局配置逻辑删除字段名
    logic-delete-field: deleted
    #逻辑已删除值(默认1)
    logic-delete-value: 1
    #逻辑未删除值(默认0)
    logic-not-delete-value: 0
2.在实体类和表中添加对应属性,并在属性上方添加@TableLogic注解

调用删除方法时,底层的sql语句自动转为更新语句

Mybatis-Plus逻辑删除

Mybatis-Plus逻辑删除

逻辑删除

物理删除∶从数据库中直接移除
逻辑删除︰再数据库中没有被移除,而是通过一个变量来让他失效! deleted =0 => deleted = 1
管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

1、在数据库中添加deleted字段

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z30ZLVA5-1633440534749)(…/…/TyporaImages/image-20211005210904161.png)]

2、导入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

2、编写配置文件.YML

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis
    driver-class-name: com.mysql.jdbc.Driver
#配置日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  #配置逻辑删除
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0

3、编写持久类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class user implements Serializable {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @Version//乐观锁注解
    private Integer version;
    
    @TableLogic//逻辑删除
    private Integer deleted;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

4、编写mapper类

@Repository
public interface mapper extends BaseMapper <user> {

}

5、编写config配置类

//扫描mapper包
@MapperScan("com.xys.Mapper")
@EnableTransactionManagement
@Configuration//配置类
public class MybatisConfig {

    //注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }

    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
    
    //逻辑删除组件
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }
}

6、编写handle类

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert info....");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update info....");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

7、测试类

//根据Id删除
    @Test
    void delById(){
        mapper.deleteById(7L);
    }
    
    //批量删除
    @Test
    void delByList(){
        mapper.deleteBatchIds(Arrays.asList(6L,5L));
    }
    
    //根据map删除
    @Test
    void delByMap(){
        HashMap<String,Object> map=new HashMap<>();
        //自定义要查询
        map.put("name","c");
        mapper.deleteByMap(map);
    }

8、测试结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PwWfuNX7-1633440534753)(…/…/TyporaImages/image-20211005211856448.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1RxbnsS3-1633440534758)(…/…/TyporaImages/image-20211005211919283.png)]

9、再次查询的时候

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@68699afc] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1126074033 wrapping com.mysql.cj.jdbc.ConnectionImpl@35c4e864] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email,version,deleted,create_time,update_time FROM user WHERE id=? AND deleted=0 
==> Parameters: 7(Long)
<==      Total: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@68699afc]

但数据库依然存在数据

ameters: 7(Long)
<== Total: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@68699afc]


<font color='red'>但数据库依然存在数据</font>

以上是关于MyBatis-Plus逻辑删除的主要内容,如果未能解决你的问题,请参考以下文章

记录mybatis-plus逻辑删除配置无效的坑

mybatis-plus(3.0-RELEASE)逻辑删除的坑

#yyds干货盘点#mybatis-plus学习与实践逻辑删除

Mybatis-Plus:逻辑删除(@TableLogic 将数据标记为删除,而并非真正 的物理删除(非DELETE操作))

Mybatis-Plus:Sql 注⼊器⾃动填充功能逻辑删除

Mybatis-Plus:Sql 注⼊器⾃动填充功能逻辑删除