SoFunction
Updated on 2025-03-03

Practice of MyBatisPlus implementing automatic fill fields

MyBatis-Plus provides a convenient autofill feature to automatically fill certain fields when data is inserted or updated, such as creation time, update time, etc. Here are detailed instructions on how to use this feature.
The automatic filling function is implemented by implementing the interface. You need to create a class to implement this interface and define the padding logic when inserting and updating.

Official Documentation:"MyBatis-Plus Automatically Fill Fields"

【Example】Use MyBatis-Plus' autofill field function to automatically fill the data table: create_time and update_time fields.

1. Create a data table

Create a user information table (tb_user) in the MySQL database.

-- Create a database
CREATE DATABASE IF NOT EXISTS db_admin;

-- Using database
USE db_admin;

-- Determine whether the data table exists,Delete if it exists
DROP TABLE IF EXISTS tb_user;
 
-- create“User Information”Data table
CREATE TABLE IF NOT EXISTS tb_user
( 
	user_id BIGINT(20) AUTO_INCREMENT PRIMARY KEY COMMENT 'User number',
	user_account VARCHAR(50) NOT NULL COMMENT 'User Account',
	user_password VARCHAR(50) NOT NULL COMMENT 'User Password',
	blog_name VARCHAR(50) COMMENT 'Blog Information',
	blog_url VARCHAR(50) NOT NULL COMMENT 'Blog Address',
	create_time TIMESTAMP DEFAULT NULL COMMENT 'Create time',
	update_time TIMESTAMP DEFAULT NULL COMMENT 'Last modified time'
) COMMENT = 'User Information Table';

2. Define entity classes

In entity classes, the @TableField annotation must be used to mark which fields need to be automatically filled and specify the filling policy.

In the entity package, create the UserInfo class (user information entity class).

package ;

import .*;
import ;
import ;

import ;

/**
  * User information entity class
  * @author pan_junbiao
  **/
@Data
@TableName("tb_user") //Set the data table namepublic class UserInfo
{
    // Ignore other fields...
    /**
      * Creation time
      */
    @TableField(fill = )  //Fill policy: Insert the fill field    private LocalDateTime createTime;

    /**
      * Last modified time
      */
    @TableField(fill = FieldFill.INSERT_UPDATE) //Fill policy: Insert and update the fill field    private LocalDateTime updateTime;
}

FieldFill enumeration:

public enum FieldFill {
    DEFAULT,       // Not processed by default    INSERT,        // Insert fill field    UPDATE,        // Update the fill field    INSERT_UPDATE  // Insert and update fill fields}

3. Implement the MetaObjectHandler interface

Create a class to implement the MetaObjectHandler interface and override the insertFill and updateFill methods.

In the handler package, create the MyMetaObjectHandler class (MyBatis-plus auto-fill field processing class).

package ;

import ;
import ;
import ;

import ;
import ;
import ;

/**
  * MyBatis-plus autofill field processing class
  * @author pan_junbiao
  **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler
{
    /**
      * New operation: Perform automatic filling
      */
    @Override
    public void insertFill(MetaObject metaObject) {
        (metaObject, "createTime", , ());
        (metaObject, "updateTime", , ());
    }

    /**
      * Modify operation: perform automatic filling
      */
    @Override
    public void updateFill(MetaObject metaObject) {
        (metaObject, "updateTime", , ());
    }

    /**
      * Forced fill
      * Official original text: The default method strategy provided by MetaObjectHandler is: if the attribute has a value, it will not be overwritten, and if the fill value is null, it will not be filled.
      * So here to modify the strategy method, remove the judgment that the attribute is null, and implement forced fill
      */
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = ();
        if ((obj)) {
            (fieldName, obj);
        }
        return this;
    }
}

Notice:

Make sure that the MyMetaObjectHandler class is managed by Spring and can be implemented through @Component or @Bean annotation.

4. Things to note

  • Automatic filling is to directly set values ​​for the properties of the entity class.
  • If the property has no value, it will be null when entering the library.
  • The default method strategy provided by MetaObjectHandler is: if the property has a value, it will not be overwritten, and if the fill value is null, it will not be filled.
  • The field must declare the @TableField annotation and set the fill property to select the fill policy.
  • The fill processor needs to be declared as @Component or @Bean in Spring Boot.
  • Use the strictInsertFill or strictUpdateFill methods to distinguish padding logic based on annotation, field name, and field type.
  • If no distinction is required, you can use the fillStrategy method.
  • When update(T entity, Wrapper<T> updateWrapper), entity cannot be empty, otherwise the automatic filling will fail.
  • It will not be automatically filled during update(Wrapper<T> updateWrapper) and field conditions need to be assigned manually.

This is the end of this article about the practice of MyBatisPlus in implementing automatic fill fields. For more related contents of MyBatisPlus in automatic fill fields, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!