SoFunction
Updated on 2025-03-08

mybatisplus implements interface MetaObjectHandler to automatically fill field values

MetaObjectHandler is an interface provided by MyBatis-Plus, which is used to handle metaObject-level operations. It is mainly used to automatically fill fields, such as automatically fill fields such as creation time and modification time when inserting or updating data. By implementing the MetaObjectHandler interface, you can customize the fields' fill logic.

Here is an example of how to implement the MetaObjectHandler interface to automatically fill fields:

Create a class that implements MetaObjectHandler:

import ;
import ;

import ;

@Component
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        (metaObject, "createTime", , ());
        (metaObject, "updateTime", , ());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        (metaObject, "updateTime", , ());
    }
}

In this example, the insertFill method will be called before inserting the data, and the updateFill method will be called before updating the data. strictInsertFill and strictUpdateFill methods are used to fill the specified field and will not be overwritten if the field already has a value.

Declare fields that need to be automatically populated in the entity class:

import ;
import ;
import ;
import ;

@TableName("user")
public class User {

    @TableField(fill = )
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    //Omit other fields and getter/setter...}

Here, the fill property of the @TableField annotation specifies the fill policy of the field, indicating that it is only filled on insertion, and FieldFill.INSERT_UPDATE means that it is filled on insertion and update.
Configure MetaObjectHandler:

In the Spring Boot project, since we use the @Component annotation, Spring will automatically scan and register this class. If you are using a non-Spring Boot project, you need to manually configure the bean.

Through the above steps, MyBatis-Plus will automatically fill in createTime and updateTime fields when performing insertion or update operations, without explicitly setting the values ​​of these fields in the business code.

This is the article about the automatic filling field values ​​of mybatisplus implementing interface MetaObjectHandler. For more related contents of mybatisplus auto-filling field values, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!