About the plug-in mechanism of Mybatis-Plus

1. Autofill

Some data is often encountered in the project, and it is filled in the same way every time, such as the record creation time, update time, etc.

We can use the autofill function of MyBatis Plus to complete the assignment of these fields:

1.1 Principle

  • Implement the meta-object processor interface: com.baomidou.mybatisplus.core.handlers.MetaObjectHandler, to determine the specific operation of filling
  • Annotate filled fields: @TableField(fill = ...)determine when fields are filled
    • FieldFill.INSERT: Insert a fill field
    • FieldFill.UPDATE: update the fill field
    • FieldFill.INSERT_UPDATE: Insert and update fill fields

1.2 Basic Operation

  • Step 1: Modify the table to add fields
alter table tmp_customer add column create_time date;
alter table tmp_customer add column update_time date;
  • Step 2: Modify JavaBean
package com.czxy.mp.domain;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.util.Date;

/**
 * Created by nannan.
 */
@Data
@TableName("tmp_customer")
public class Customer {
    
    
    @TableId(type = IdType.AUTO)
    private Integer cid;
    private String cname;
    private String password;
    private String telephone;
    private String money;

    @TableField(value="create_time",fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(value="update_time",fill = FieldFill.UPDATE)
    private Date updateTime;

}

  • Step 3: Write the processing class

    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-ldK08LSb-1640089949121)(assets/image-20200914121135941.png)]

package com.czxy.mp.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by nannan.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    
    /**
     * 插入填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("createTime", new Date(), metaObject);
    }

    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

  • Step Four: Test
    @Test
    public void testInsert() {
    
    
        Customer customer = new Customer();
        customer.setCname("测试888");

        customerMapper.insert(customer);
    }

    @Test
    public void testUpdate() {
    
    
        Customer customer = new Customer();
        customer.setCid(11);
        customer.setTelephone("999");

        customerMapper.updateById(customer);
    }

2. Optimistic locking

2.1 What is an optimistic lock

  • When a record is to be updated, it is hoped that this record has not been updated by others

  • Optimistic lock implementation:

  • When fetching records, get the current version
  • When updating, bring this version
  • When performing an update, set version = newVersion where version = oldVersion
  • If the version is incorrect, the update fails

2.2. Implementation

  • Step 1: Modify the table structure and add a version field

  • Step 2: Modify the JavaBean and add the version attribute

  package com.czxy.mp.domain;
  
  import com.baomidou.mybatisplus.annotation.*;
  import lombok.Data;
  
  /**
   * Created by nannan.
   */
  @Data
  @TableName("tmp_customer")
  public class Customer {
    
    
      @TableId(type = IdType.AUTO)
      private Integer cid;
      private String cname;
      private String password;
      private String telephone;
      private String money;
      @Version
      @TableField(fill = FieldFill.INSERT)
      private Integer version;
  }
  
  • Step 3: Add the default insert value of the version to the meta object processor interface (to ensure that the version has data)
package com.czxy.mp.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by nannan.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    
    /**
     * 插入填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("version", 1, metaObject);
    }

    /**
     * 更新填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

  • Step 4: Modify MybatisPlusConfig to enable optimistic locking
package com.czxy.mp.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by nannan.
 */
@Configuration
public class MybatisPlusConfig {
    
    
     */
    /**
     * 配置插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
    
    

        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return mybatisPlusInterceptor;
    }
}

  • Step Five: Test
    • Add one first to ensure that the version has data
    • updating the article
    @Test
    public void testUpdate() {
    
    
        Customer customer = new Customer();
        customer.setCid(14);
        customer.setCname("测试999");
        // 与数据库中数据一致,将更新成功,否则返回失败。
        customer.setVersion(1);

        int i = customerMapper.updateById(customer);
        System.out.println(i);
    }

2.3 Precautions

  • Supported data types are only: int, Integer, long, Long, Date, Timestamp, LocalDateTime
  • under integer typenewVersion = oldVersion + 1
  • newVersionwill be written back entityinto
  • Only updateById(id)the and update(entity, wrapper)methods are supported
  • update(entity, wrapper)Under the method , wrapperit cannot be reused!!!

3 Tombstone

3.1 What is tombstone

  • Logical deletion, also known as deletion. It is to provide a field in the table for whether the record is deleted, but the actual data has not been deleted.

3.2 Implementation

  • Step 1: Modify the table structure and add the deleted field

  • Step 2: Modify the JavaBean and add it to the deleted field@TableLogic

    package com.czxy.mp.domain;
    
    import com.baomidou.mybatisplus.annotation.*;
    import lombok.Data;
    
    /**
     * Created by nannan.
     */
    @Data
    @TableName("tmp_customer")
    public class Customer {
          
          
        @TableId(type = IdType.AUTO)
        private Integer cid;
        private String cname;
        private String password;
        private String telephone;
        private String money;
        @Version
        @TableField(fill = FieldFill.INSERT)
        private Integer version;
    
        @TableLogic
        @TableField(fill = FieldFill.INSERT)
        private Integer deleted;
    }
    
    

* 步骤三:添加数据时,设置默认“逻辑未删除值”


```java
  package com.czxy.mp.config;
  
  import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  import org.apache.ibatis.reflection.MetaObject;
  import org.springframework.stereotype.Component;
  
  import java.util.Date;
  
  /**
   * Created by nannan.
   */
  @Component
  public class MyMetaObjectHandler implements MetaObjectHandler {
      /**
       * 插入填充
       * @param metaObject
       */
      @Override
      public void insertFill(MetaObject metaObject) {
          this.setFieldValByName("createTime", new Date(), metaObject);
          this.setFieldValByName("version", 1, metaObject);
          this.setFieldValByName("deleted", 0, metaObject);
      }
  
      /**
       * 更新填充
       * @param metaObject
       */
      @Override
      public void updateFill(MetaObject metaObject) {
          this.setFieldValByName("updateTime", new Date(), metaObject);
      }
  }
  
  • Step Four: Test
      @Test
      public void testDelete() {
    
    
          // 删除时,必须保证deleted数据为“逻辑未删除值”
          int i = customerMapper.deleteById(12);
          System.out.println(i);
      }

3.3 Global configuration

  • If you use global configuration, you don't need to use annotations@TableLogic
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # 局逻辑删除的实体字段名
      logic-delete-value: 1  # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

insert image description here

Guess you like

Origin blog.csdn.net/weixin_48143996/article/details/122072655