Explain in detail the use of @TableLogic tombstone annotation in MybatisPlus

@TableLogic annotation

@TableLogic: Indicates logical deletion annotation
Effect: When adding this annotation to the field and then executing the delete method of BaseMapper, the delete method will become a modification

例:
  实体类:
       @TableLogic
      private Integer del;

   service层:
      调用BaseMapperdeleteById(id);

 执行是效果:

      加@TableLogic的情况下
      走 Update 表名 set 加注解的列=值 where del=
       不加@TableLogic的情况下
      走 delete from 表名 where del=

 @TableLogic注解参数

    value = "" 默认的原值
    delval = "" 删除后的值
    @TableLogic(value="原值",delval="改值")

2. Notes

@TableLogic is used to implement database data logical deletion

Note that this annotation only works for automatically injected sql

3. @TableLogic restrictions on CIUD

3.1 Insert

no limit

3.2 Search (select)

The @TableLogic annotation will add conditions to the where condition of the select statement to filter out deleted data

And the where condition generated by wrapper.entity will ignore this field

SELECT` `user_id,``name``,sex,age,deleted ``FROM` `user` `WHERE` `user_id=1 ``AND` `deleted=``'0'

3.3 update

The @TableLogic annotation will add conditions after the where condition of the update statement to prevent updating to deleted data

And the where condition generated by wrapper.entity will ignore this field

update` `user` `set` `deleted=1 ``where` `id = 1 ``and` `deleted=0

3.4 Delete

The @TableLogic annotation will turn the delete statement into an update statement

update` `user` `set` `deleted=1 ``where` `id = 1 ``and` `deleted=0

4. Description of @TableLogic field type support:

All data types are supported (Integer, Boolean, LocalDateTime are recommended)

If the database field uses datetime, the logical undeleted value and deleted value can be configured as a string null, and the other value can be configured as a function to get the value such as now()

appendix:

(1) Logical deletion is a solution to facilitate data recovery and protect the value of data itself, but it is actually deletion.

(2) If you need to check it out frequently, you should not use logical deletion, but use a state to represent it.

5. Property description

5.1 value

Used to specify logical undeleted values, the default is an empty string

5.2 delval

Used to specify the tombstone value, the default is an empty string.

6. Implemented in the configuration file

Of course, you can also not specify the value of the value and delval attributes in the @TableLogic annotation. Use the global tombstone configuration information, the configuration is as follows:

# application.yml
mybatis-plus:
  global-config:
    db-config:
      # 全局逻辑删除的实体字段名 (since 3.3.0, 配置后可以忽略 @TableLogic 中的配置)
      logic-delete-field: flag
      # 逻辑已删除值(默认为 1)
      logic-delete-value: 1
      # 逻辑未删除值(默认为 0)
      logic-not-delete-value: 0

7. Code practice

7.1 Code practice process

We add a deleted field to the user data table.

If the value of this field is 1, it means that the record is deleted. If the value of this field is 0, it means that the record has not been deleted

1. Add a deleted field to the user data table, the sql is as follows:

-- 添加一个 deleted 字段,实现逻辑删除
ALTER TABLE `user`
ADD COLUMN `deleted`  varchar(1) NULL DEFAULT 0 COMMENT '是否删除(1-删除;0-未删除)';

2. Create the entity class AnnotationUser7Bean of the user table

Use the @TableLogic annotation to specify the deleted member variable as a tombstone field

import com.baomidou.mybatisplus.annotation.*;
 
@TableName(value = "user")
public class AnnotationUser7Bean {
    
    
   @TableId(value = "user_id", type = IdType.AUTO)
   private int userId;
    
   @TableField("name")
   private String name;
    
   @TableField("sex")
   private String sex;
    
   @TableField("age")
   private Integer age;
    
   @TableLogic(value = "0", delval = "1")
   private String deleted;
    
   // 忽略 getter 和 setter 方法
    
   @Override
   public String toString() {
    
    
      return "UserBean{" +
            "userId=" + userId +
            ", name='" + name + '\'' +
            ", sex='" + sex + '\'' +
            ", age=" + age +
            ", deleted=" + deleted +
            '}';
   }
}

In the above code, use the @TableLogic annotation to specify the deleted member variable as a logical deletion field

@TableLogic(value = "0", delval = "1")
private String deleted;

3. Client code, first query whether the user with user ID 1 exists

If it exists, delete the user information

Then, query the user information whose user ID is less than 10

package com.hxstrive.mybatis_plus.simple_mapper.annotation;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxstrive.mybatis_plus.mapper.AnnotationUser7Mapper;
import com.hxstrive.mybatis_plus.model.AnnotationUser7Bean;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
class AnnotationDemo7 {
    
    
 
    @Autowired
    private AnnotationUser7Mapper userMapper;
 
    @Test
    void contextLoads() throws Exception {
    
    
        // 删除用户ID为1的用户信息
        AnnotationUser7Bean oldUserBean = userMapper.selectById(1);
        if(null != oldUserBean) {
    
    
            userMapper.deleteById(oldUserBean.getUserId());
        }
 
        // 查询用户信息
        QueryWrapper<AnnotationUser7Bean> wrapper = new QueryWrapper<>();
        wrapper.lt("user_id", 10);
        for(AnnotationUser7Bean item : userMapper.selectList(wrapper)) {
    
    
            System.out.println(item);
        }
    }
 
}

7.2 Database code execution instructions

Query user information based on user ID

Preparing: SELECT user_id,name,sex,age,deleted FROM user WHERE user_id=? AND deleted='0'
Parameters: 1(Integer)

Delete user information based on user ID

sql is an update statement, this is because we use a logical delete, not a physical delete

Preparing: UPDATE user SET deleted='1' WHERE user_id=? AND deleted='0'
Parameters: 1(Integer)

Query user information whose user ID is less than 10

Preparing: SELECT user_id,name,sex,age,deleted FROM user WHERE deleted='0' AND (user_id < ?)
Parameters: 10(Integer)

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/131143093