MybatisPlus - [05] 邏輯刪除

HOUHUILIN發表於2024-06-12

題記部分

一、物理刪除&邏輯刪除

物理刪除:delete from table_name where xxx = ?;

邏輯刪除:update table_name set deleted = 0 where xxx = ?;

二、測試

(1)增加邏輯刪除欄位deleted(預設1,1:存在,0:刪除)

alter table user add column deleted int(1) default 1 comment '邏輯刪除' after version;

(2)POJO實體類增加屬性

package com.harley.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.Date;

/**
 * @author harley
 * @date 2024/06/06 17:30
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {

    @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;
}

(3)配置 application.properties

spring.application.name: mybatis-plus
# 資料庫連線配置
spring.datasource:
  driver-class-name: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&userUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
  username: root
  password: '!QAZ2wsx'


mybatis-plus:
  global-config:
    # 配置邏輯刪除 
    db-config:
      # 刪除為0
      logic-delete-value: 0
      # 存在為1
      logic-not-delete-value: 1
  configuration:
    # 配置日誌
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

(4)測試刪除

  • 首先查詢user表中的資料

MybatisPlus - [05] 邏輯刪除

  • 漩渦鳴人開啟仙人模式幹掉6個佩恩
@Test
void testDelete(){
    int res = userMapper.deleteBatchIds(Arrays.asList(7L,8L,9L,10L,11L,12L));
    if (res > 0){
        System.out.println("漩渦鳴人開啟仙人模式幹掉了"+res+"個佩恩");
    }
}

MybatisPlus - [05] 邏輯刪除

MybatisPlus - [05] 邏輯刪除

— 業精於勤荒於嬉,行成於思毀於隨 —

相關文章