MyBatis-Plus 邏輯刪除

邏輯刪除是爲了方便數據恢復和保護數據本身價值等等的一種方案。使用一個狀態來表示數據是否已被刪除。

SpringBoot 配置方式:

application.yml 加入配置(如果你的默認值和mp默認的一樣,該配置可無):

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  #全局邏輯刪除字段值 3.3.0開始支持,詳情看下面。
      logic-delete-value: 1 # 邏輯已刪除值(默認爲 1)
      logic-not-delete-value: 0 # 邏輯未刪除值(默認爲 0)

註冊 Bean(3.1.1開始不再需要這一步):

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfiguration {

    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
}

實體類字段上加上@TableLogic註解

@TableLogic
private Integer deleted;

效果: 使用mp自帶方法刪除和查找都會附帶邏輯刪除功能 (自己寫的xml不會)

example
刪除時 update user set deleted=1 where id =1 and deleted=0
查找時 select * from user where deleted=0

全局邏輯刪除: 3.3.0開始支持

如果公司代碼比較規範,比如統一了全局都是flag爲邏輯刪除字段。

使用此配置則不需要在實體類上添加 @TableLogic。

但如果實體類上有 @TableLogic 則以實體上的爲準,忽略全局。 即先查找註解再查找全局,都沒有則此表沒有邏輯刪除。

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  #全局邏輯刪除字段值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章