In daily development, database tables usually contain some fields that are automatically maintained by the system, such as: creation time, update time, operator, etc. To reduce duplicate code to manually maintain these fields, MyBatis-Plus provides an autofill feature to help developers automatically assign values to certain fields when inserting or updating data.
1. Introduction to MyBatis-Plus Autofill
The automatic fill feature provided by MyBatis-Plus can automatically set values for specified fields when the database is inserted or updated without requiring manual delivery every time. For example:
- Automatically fill the creation time when record insertion
created_at
。 - Automatically fill in update time when recording updates
updated_at
。 - Automatically fill the operation user ID or some other fixed value.
MyBatis-Plus by@TableField
The annotationfill
Attributes andMetaObjectHandler
Interface to realize automatic filling.fill
Attribute is used to specify whether the field is automatically filled when inserted or updated, andMetaObjectHandler
It is an interface used to implement automatic fill logic.
2. Automatic filling configuration steps
2.1 Annotate fields that need to be automatically filled in the entity class
MyBatis-Plus by@TableField(fill = ...)
Annotation is used to annotate the fields that need to be automatically filled and specify the filling policy for the field. Common filling strategies are:
-
: Automatically fill when inserted.
-
: Automatically fill when updated.
-
FieldFill.INSERT_UPDATE
: Automatically fill when inserting and updating.
Example:
import ; import ; import ; import ; @Data public class User { private Integer id; private String username; @TableField(fill = ) private LocalDateTime createdAt; // Automatically fill when inserting @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updatedAt; // Automatically fill when inserting and updating}
-
createdAt
: Automatically fill in the current time when inserting a record. -
updatedAt
: Automatically fill the current time when inserting and updating records.
2.2 Creating an autofill processor
MyBatis-Plus providesMetaObjectHandler
Interface, developers can implement theinsertFill
andupdateFill
Methods customize the fill logic.
Example:
import ; import ; import ; import ; @Component public class MyMetaObjectHandler implements MetaObjectHandler { // Automatically fill when inserting @Override public void insertFill(MetaObject metaObject) { (metaObject, "createdAt", LocalDateTime::now, ); // Creation time (metaObject, "updatedAt", LocalDateTime::now, ); // Update time } // Automatically fill when updated @Override public void updateFill(MetaObject metaObject) { (metaObject, "updatedAt", LocalDateTime::now, ); // Update time } }
-
strictInsertFill
: Used to automatically fill the specified fields during insertion operation. -
strictUpdateFill
: Used to automatically populate the specified fields during update operations.
existinsertFill
In the method,createdAt
andupdatedAt
The field will automatically fill in the current time when inserted. And inupdateFill
In the method,updatedAt
The field will automatically fill in the current time when it is updated.
2.3 Complete Example
Here is a complete MyBatis-Plus autofill example, including entity classes, fill processors, and test code:
1. User Entity Class
import ; import ; import ; import ; import ; import ; @Data public class User { @TableId(type = ) private Integer id; private String username; @TableField(fill = ) private LocalDateTime createdAt; // Automatically fill when created @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updatedAt; // Automatically fill when creating and updating}
2. Automatic filling processor
import ; import ; import ; import ; @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { (metaObject, "createdAt", LocalDateTime::now, ); (metaObject, "updatedAt", LocalDateTime::now, ); } @Override public void updateFill(MetaObject metaObject) { (metaObject, "updatedAt", LocalDateTime::now, ); } }
3. UserMapper interface
import ; import ; import ; @Mapper public interface UserMapper extends BaseMapper<User> { }
4. Test code
import ; import ; import ; import ; import ; @Component public class MyTestRunner implements CommandLineRunner { @Autowired private UserMapper userMapper; @Override public void run(String... args) throws Exception { // Automatic filling during test insertion User user = new User(); ("John Doe"); (user); ("Inserted user: " + user); // Automatically fill when testing is updated ("Jane Doe"); (user); ("Updated user: " + user); } }
In the above test code:
- When inserting a new user,
createdAt
andupdatedAt
The fields will be automatically filled. - When updating users,
updatedAt
Fields will be automatically updated.
3. Detailed explanation of the automatic filling strategy
3.1 Automatic filling policy options
@TableField
Annotatedfill
Attributes support the following automatic filling strategies:
-
: Automatically fill only when inserted.
-
: Automatically populate only when updated.
-
FieldFill.INSERT_UPDATE
: Automatically fill when inserting and updating.
@TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updatedAt;
3.2 Detailed explanation of MetaObjectHandler method
strictInsertFill
: Used to automatically fill fields when inserting, accepting 4 parameters: MetaObject, field name, fill value and field type.
(metaObject, "createdAt", LocalDateTime::now, );
strictUpdateFill
: Used to automatically populate fields when updated.
(metaObject, "updatedAt", LocalDateTime::now, );
If you do not need to distinguish between insertion and update, you can use it directlysetFieldValByName
method:
("updatedAt", (), metaObject);
3.3 Manually trigger fill
In some scenarios, it may be desirable to manually trigger the autofill logic in the code, which can be usedfillStrategy
method.
MetaObject metaObject = (user); (metaObject, "updatedAt", ());
4. Notes on automatic filling
4.1 Database default value conflict
Conflicts may occur if the database field has default values and the entity class uses auto-filling at the same time. The solution is to remove the default value from the database and rely entirely on MyBatis-Plus for auto-filling.
4.2 MetaObjectHandler must be registered as Spring Bean
Automatic filling processor classMetaObjectHandler
Must be managed by Spring container (that is, use@Component
Annotation), otherwise the automatic filling will not take effect.
4.3 Overwrite existing values
MyBatis-Plus will automatically mark it when inserting or updating.fill
Assign values to fields, but if these fields already have values, MyBatis-Plus will not overwrite the existing values by default.
. To overwrite an existing value, you can usestrictInsertFill
orstrictUpdateFill
。
5. Common usage scenarios
5.1 Automatically fill in creation time and update time
In most database tables, there will becreated_at
andupdated_at
Field, used to record the creation time and last update time of data. Through the autofill function, MyBatis-Plus can easily achieve automatic maintenance of these two fields.
5.2 Operator auto-filling
In scenarios such as operation logs, audit systems, etc., it is usually necessary to record the operator ID. The current user ID can be automatically obtained and filled into the table when inserting and updating records through the automatic fill mechanism.
@Override public void insertFill(MetaObject metaObject) { (metaObject, "operatorId", () -> getCurrentUserId(), ); }
6. Summary
MyBatis-Plus' automatic filling function can greatly simplify development work. It can automatically fill fields when inserting and updating through simple annotations and configurations, reducing the amount of code to manually maintain duplicate fields.
-
@TableField(fill = ...)
: Automatic fill policy for specifying fields, supporting insert, update, and insert updates. -
MetaObjectHandler
: Customize the interface for automatic filling logic, which developers can implementinsertFill
andupdateFill
Method controls fill behavior.
This is the end of this article about the implementation example of MyBatis-Plus autofill. For more related content on MyBatis-Plus autofill, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!