MyBatis-Plus provides many enhancements, among whichMetaObjectHandler
is a key interface for automatically populating entity fields. This article will discuss in detailMetaObjectHandler
The usage scenarios, working principles, specific implementations and internal mechanisms of .
1. Overview
MetaObjectHandler
The main function is to automatically populate fields in the entity class when database operations (such as insertion and update), especially those that do not require manual assignment of users. Its typical application scenarios include automatic filling of public fields such as creation time, update time, and operator.
1.1 Design concept
In modern applications, the maintenance of database records often involves public fields such as "create time" and "update time". If you manually process these fields in each insert or update operation, it is not only prone to errors, but also adds redundancy to the code.MetaObjectHandler
The original design intention was to simplify this process, making the processing of these common fields automated and unaware.
1.2 Advantages of automatic filling
Automatic filling not only reduces code redundancy, but also improves data consistency and integrity. With automatic fill, developers can ensure that each database operation follows the same rules, avoiding human errors. In addition, automatic filling can improve development efficiency and enable developers to focus on the implementation of business logic.
2. Interface design
MetaObjectHandler
The interface provides several core methods for handling automatic filling of insert and update operations. The default in MyBatis-PlusMetaObjectHandler
The implementation follows a strict fill strategy, that is, the fields will be automatically filled only when specific conditions are met.
2.1 Core Methods
MetaObjectHandler
The following core methods are provided:
-
void insertFill(MetaObject metaObject)
: Automatically fill fields when processing insertion. -
void updateFill(MetaObject metaObject)
: Automatically populate fields when processing updates. -
MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
: Used to set the value of the specified field. -
Object getFieldValByName(String fieldName, MetaObject metaObject)
: Gets the value of the specified field. -
TableInfo findTableInfo(MetaObject metaObject)
: according toMetaObject
Get the corresponding table information.
2.2 Default implementation
MyBatis-Plus providesMetaObjectHandler
The default implementation class. Developers can customize the field fill logic when inserting and updating by inheriting this class.
2.3 Strict filling strategy
By default,MetaObjectHandler
Following a strict fill strategy, this means that the value will not be overwritten if the field already has a value, but will be filled only when the field is empty. This strategy ensures data consistency and prevents unnecessary overwriting.
Implementation of MetaObjectHandler
Developers can implement itMetaObjectHandler
Interface custom field fill logic. Here is an example that implements automatic fill of creation time and update time.
3.1 Implementation Example
To better manage constants, we cancreateTime
、updateTime
Equal string constants are encapsulated into a constant class:
public class FieldConstants { public static final String CREATE_TIME = "createTime"; public static final String UPDATE_TIME = "updateTime"; public static final String CREATOR = "createdBy"; public static final String UPDATER = "updatedBy"; }
Then inMetaObjectHandler
Use these constants in the implementation:
import ; import ; import ; import ; @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); (metaObject, FieldConstants.UPDATE_TIME, , ()); } @Override public void updateFill(MetaObject metaObject) { (metaObject, FieldConstants.UPDATE_TIME, , ()); } }
In the above code, we passstrictInsertFill
andstrictUpdateFill
The method implements automatic filling of creation time and update time.
3.2 Customize the policy
In addition to the default policy, developers can also usefillStrategy
andstrictFillStrategy
Method customizes the fill logic of fields. By default, these methods will be populated only when the field is empty, avoiding overwriting existing values.
4. Application scenarios of automatic filling
MetaObjectHandler
It is widely used in actual development, especially for systems that require the management of a large number of public fields. The following are some typical application scenarios, which showMetaObjectHandler
How to help developers reduce duplicate code and ensure data consistency and integrity.
4.1 Automatic maintenance of timestamps
In most enterprise-level applications, almost all data tables containCreation time
(create_time
) andUpdate time
(update_time
) field. Manually updating these fields is not only cumbersome, but also prone to errors. For example, developers may forget to modify it when updating records.Update time
field, which makes the data timeliness cannot be guaranteed. To avoid this,MetaObjectHandler
Provides a mechanism to automatically maintain timestamps.
ByMetaObjectHandler
Defines a unified timestamp fill logic in , when an insertion or update operation occurs,create_time
andupdate_time
The field will automatically fill in the current time. This not only ensures consistency of timestamps, but also prevents developers from repeatedly writing similar time-processing logic in their code.
Example:
@Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); } @Override public void updateFill(MetaObject metaObject) { (metaObject, FieldConstants.UPDATE_TIME, , ()); }
In the above code,insertFill
Methods to ensurecreateTime
The field is automatically set to the current time when a new record is inserted, andupdateFill
The method ensures that every time the record is updated,updateTime
Fields are automatically updated.
4.2 Automatic filling of operator information
In many systems involving user operations, recording operator information is a very important requirement. Typical examples include the order management system of e-commerce platforms, the backend administrator operation record system, etc. Each time an insertion or update operation is performed, it is usually necessary to record the operator information, such ascreated_by
andupdated_by
Field. These fields are used to track which user data was created or updated.
MetaObjectHandler
Use the information of the currently logged in user and automatically populate it intocreated_by
andupdated_by
in the field. This ensures that each data record can be traced back to the specific operator, thereby improving the auditability and security of the system.
Example:
@Override public void insertFill(MetaObject metaObject) { String currentUser = ().getAuthentication().getName(); (metaObject, , , currentUser); } @Override public void updateFill(MetaObject metaObject) { String currentUser = ().getAuthentication().getName(); (metaObject, , , currentUser); }
In this example, whenever the user performs an insert or update operation, the current user's information will be automatically filled tocreatedBy
andupdatedBy
In the field, no manual processing is required for developers.
4.3 Automatic processing of logical deletion identifiers
Logical deletion is a common deletion strategy in enterprise-level applications. It keeps records in the database and usesis_deleted
The field identifies whether the record has been deleted, rather than physically deleting the data directly. The advantage of this strategy is that it can restore the accidentally deleted data at any time while retaining the historical record of the data.
MetaObjectHandler
The logical deletion identifier can be automatically processed, and the deletion operation will be automatically performed.is_deleted
The field is set totrue
. This prevents developers from missing this identity when performing a delete operation, while ensuring consistency of logical deletion.
Example:
@Override public void updateFill(MetaObject metaObject) { Boolean isDeleted = (Boolean) ("isDeleted"); if (isDeleted == null || !isDeleted) { (metaObject, "isDeleted", , true); } }
In this code example,MetaObjectHandler
examineisDeleted
Is the field atrue
, If not, it will be automatically set when performing logical deletionisDeleted
fortrue
。
5. MetaObjectHandler's expansion capability
MyBatis-Plus provides rich expansion capabilities, makingMetaObjectHandler
Able to customize according to complex business needs. Developers can extendMetaObjectHandler
The function of implements more complex field filling logic, thereby meeting the needs of various specific scenarios.
5.1 Dynamic processing of table structure
In some scenarios, the structure of the data table may change according to business needs. For example, the existence or type of certain fields may vary depending on different business models.MetaObjectHandler
Provides the ability to access table structure, and developers can dynamically decide how to populate fields according to different table structures.
By callingfindTableInfo
method,MetaObjectHandler
You can obtain the table information of the current operation object. Developers can design specific fill logic for different table structures based on this information. For example, for some optional fields, you can choose whether to fill it according to the existence or not of the fields in the table.
Example:
@Override public void insertFill(MetaObject metaObject) { TableInfo tableInfo = (().getClass()); if (().stream().anyMatch(field -> ().equals("customField"))) { (metaObject, "customField", , "DefaultValue"); } }
In this example,MetaObjectHandler
Will check whether the table existscustomField
Field, if present, will automatically fill in the default value.
5.2 Context-based field fill
In actual development, the field filling logic sometimes needs to rely on context information, such as the currently requested user, the current organizational structure or system configuration parameters, etc.MetaObjectHandler
This information can be obtained dynamically when filling fields by injecting relevant context services, thereby achieving more flexible filling logic.
Developers can inject context information of the service layer (such as user information, configuration management services, etc.) intoMetaObjectHandler
In , when performing field filling, the field value is dynamically set according to the current context. This approach is particularly suitable for complex enterprise applications, such as field filling in multi-tenant systems.
Example:
@Service public class CustomMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { Long currentUser = (); (metaObject, , , currentUser); } @Override public void updateFill(MetaObject metaObject) { Long currentUser = (); (metaObject, , , currentUser); } }
In this example,CustomMetaObjectHandler
useUserService
Get current user information and dynamically fill it when performing insert and update operations.createdBy
andupdatedBy
Field.
5.3 Condition-based fill strategy
In some complex business scenarios, the filling of fields may depend on multiple conditions. For example, the fill of a field may be based on the current operation type (insert or update), or based on a specific state of the data. To deal with these complex scenarios,MetaObjectHandler
Provides an extension methodfillStrategy
andstrictFillStrategy
, developers can implement customized fill strategies according to business needs.
These strategies allow developers to define complex conditional judgment logic and field fills only when specific conditions are met. In this way, refined control can be achieved to ensure that the field fill logic is accurately in line with business needs.
Example:
@Override public void insertFill(MetaObject metaObject) { if (shouldFillCreatedBy(metaObject)) { (metaObject, , , ()); } } private boolean shouldFillCreatedBy(MetaObject metaObject) { // For example: Fill only if the field is empty and the operation type is insert return () == null && isInsertOperation(metaObject); } private boolean isInsertOperation(MetaObject metaObject) { // Determine whether it is an insertion operation return true; // Simplified example}
In this example,shouldFillCreatedBy
The method defines a conditional logic that is only populated when a specific condition is met.createdBy
Field. In this way, developers can implement complex field fill logic to adapt to various business scenarios.
6. Best Practices
To make full use ofMetaObjectHandler
, Developers should follow some best practices when using it, which help reduce errors and improve system maintainability and performance.
6.1 Avoid repeated filling
In realizingMetaObjectHandler
hour
, developers should try to avoid repeated filling of the same field. Repeated fill not only increases the performance overhead of the system, but may also lead to data inconsistency. For example, in some scenarios, if the developer accidentally populates the same field multiple times during the update operation, the original correct value may be overwritten, resulting in data errors.
To avoid this, developers can add necessary conditional checks to the fill logic to make sure that the fields are populated only if needed. For example, whether to perform a fill operation can be decided by checking whether a field is empty or whether a field has been filled.
Example:
@Override public void updateFill(MetaObject metaObject) { if ((FieldConstants.UPDATE_TIME) == null) { (metaObject, FieldConstants.UPDATE_TIME, , ()); } }
In this example,updateFill
Methods first checkupdateTime
Whether the field is empty is to fill the field only if the field is empty, thereby avoiding repeated fill.
6.2 Unified management of public fields
For those public fields that need to be automatically filled, it is recommended that developers pass the project uniformly.MetaObjectHandler
Conduct management. Unified management not only reduces code duplication, but also improves code maintainability and consistency. By centrally defining and managing the fill logic of public fields, developers can ensure that all public fields in relevant tables follow a consistent fill strategy to avoid omissions or inconsistencies.
This centralized management method can also facilitate developers to make global modifications in the project. For example, when you need to adjust the fill logic of a common field, you only need toMetaObjectHandler
If modified once, updates will be automatically applied to all places where this logic is used, reducing maintenance costs.
6.3 Regularly check the fill logic
As the project evolves, business requirements tend to change, and the filling logic may also need to be adjusted accordingly. Therefore, developers should check regularlyMetaObjectHandler
The implementation of ensures that it meets current business needs and system design.
For example, when the system adds new business modules or modifys the data table structure, it may be necessary toMetaObjectHandler
The logic in is updated to adapt to these changes. Through regular code reviews and testing, developers can promptly identify and fix potential problems, ensuring that the system remains efficient and stable during long-term operation.
7. Deeply understand the internal mechanism of MetaObjectHandler
MetaObjectHandler
The core mechanism lies inMetaObject
Operation.MetaObject
It is a key abstract in the MyBatis framework, used to encapsulate the metadata of objects (such as the getter/setter method of properties) and provides access and operational capabilities to these metadata.
7.1 How MetaObject works
MetaObject
It is a metadata operation object in MyBatis responsible for managing entity class attributes. It encapsulates the metadata of the entity class, allowing developers to dynamically obtain and set the attribute values of the entity class at runtime without directly relying on the specific implementation of the entity class.
existMetaObjectHandler
middle,MetaObject
The attribute value used to operate on entity classes. passMetaObject
The method provided,MetaObjectHandler
It is possible to read and modify properties of entity classes easily. This mechanism makesMetaObjectHandler
Ability to automatically fill or modify the value of a field when inserting and updating operations without the need to understand the specific implementation details of the entity class.
Example:
@Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); }
In this example,strictInsertFill
Method passedMetaObject
Set upcreateTime
The value of the field without directly manipulating the entity class.
7.2 Collaboration between TableInfo and MetaObjectHandler
TableInfo
It is an object used in MyBatis-Plus to describe the data table structure. It contains metadata information related to the table, such as table name, primary key field, column information, etc. existMetaObjectHandler
middle,TableInfo
Plays a bridge and helpsMetaObjectHandler
Determine the fields that need to be filled.
When dealing with complex fill logic,MetaObjectHandler
Can be passedTableInfo
Get the structure information of the current operation table, thereby deciding how to populate the fields. This collaborative relationship ensuresMetaObjectHandler
In the scenario where multiple tables and multiple fields are handled, the filling logic can be accurately executed to avoid errors caused by changes in the table structure.
Example:
TableInfo tableInfo = (().getClass());
By obtainTableInfo
,MetaObjectHandler
It can dynamically adapt to changes in different table structures, so as to handle field fills more flexibly.
7.3 Strict filling and conditional filling
MetaObjectHandler
Two main filling strategies are provided: strict filling and conditional filling. Strictly filled (strictFillStrategy
) Ensure that the fields are filled when they are empty is a relatively conservative strategy and is suitable for most scenarios where you need to ensure that fields are always filled correctly. and conditional fill (fillStrategy
) allows developers to flexibly control the fill behavior of fields according to specific conditions, which is suitable for more complex business needs.
The advantage of strict fill is its certainty, ensuring that the fields are filled correctly in every operation. Conditional filling provides greater flexibility, and can perform filling operations targeted according to different business scenarios.
Example:
@Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); } @Override public void updateFill(MetaObject metaObject) { (metaObject, FieldConstants.UPDATE_TIME, ()); }
In this example,strictInsertFill
Adopt strict filling strategies to ensurecreateTime
Fields are always filled when inserted. andfillStrategy
This allows developers to flexibly decide whether to fill in according to conditions during update operations.updateTime
Field.
8. Performance optimization
AlthoughMetaObjectHandler
The design provides great flexibility and can meet multiple business needs, but in high concurrency application scenarios, if used improperly, it may also become a performance bottleneck in the system. Therefore, in order to maintain the efficient operation of the system in a high concurrency environment, it is necessary toMetaObjectHandler
Perform some performance optimizations.
8.1 Cache TableInfo Information
TableInfo
It is an important data structure used by MyBatis-Plus to describe the database table structure. Each time an insert or update operation is performed,MetaObjectHandler
Maybe callfindTableInfo
Method to obtain table information corresponding to entity class. However, becausefindTableInfo
The internal implementation of the method may involve more calculations or lookups from the global cache. If such searches are repeated for each operation, it may lead to unnecessary performance overhead.
8.1.1 Necessity of caching
In high concurrency scenarios, the system may frequently perform insertion or update operations on the same table. If table information is required to be re-acquisitioned for each operation, it will result in repetition of resources and increase response time. ByMetaObjectHandler
A caching mechanism is introduced in the implementation, which can cache table information, thereby avoiding repeated calculations and searches. This cache can be memory-level, using JavaConcurrentHashMap
Or other efficient data structures to storeTableInfo
, and map according to the type of entity class.
8.1.2 Implementation method
A common way of implementation is toMetaObjectHandler
Maintain a static cache container in the class when it needs to be retrievedTableInfo
When , first check whether there is corresponding table information in the cache. If the cache hits, it will directly return to the cachedTableInfo
;If the cache misses, callfindTableInfo
Methods are obtained and the result is cached.
import ; import ; import ; import ; import ; public class CachedMetaObjectHandler implements MetaObjectHandler { // Cache container private static final Map<Class<?>, TableInfo> tableInfoCache = new ConcurrentHashMap<>(); @Override public void insertFill(MetaObject metaObject) { TableInfo tableInfo = getCachedTableInfo(metaObject); // Execute padding logic } @Override public void updateFill(MetaObject metaObject) { TableInfo tableInfo = getCachedTableInfo(metaObject); // Execute padding logic } private TableInfo getCachedTableInfo(MetaObject metaObject) { Class<?> clazz = ().getClass(); return (clazz, TableInfoHelper::getTableInfo); } }
In this way, the cache can be significantly reducedTableInfo
search time to improve the system's performance in high concurrency environments.
8.2 Reduce unnecessary field fills
existMetaObjectHandler
In , the filling of fields is a key process. However, not all fields need to be filled every operation, especially in high concurrency scenarios, where unnecessary field fills can lead to system performance degradation.
8.2.1 Judge the necessity of filling
Developers are implementingMetaObjectHandler
When it comes to the specific operation or condition, it should be clarified which fields need to be filled and which fields need not be filled. For example, some fields may only need to be filled in the insert operation but not in the update operation; or, some fields may only be filled in the specific state.
8.2.2 Conditional judgment and optimization
By making conditional judgments on the logic of field filling, unnecessary performance overhead can be avoided. For example, developers caninsertFill
orupdateFill
Conditional judgment is added to the method, and field filling logic is only executed when specific conditions are met. This optimization method can significantly improve the performance of the system by reducing redundant operations.
@Override public void insertFill(MetaObject metaObject) { // Fill only if the field is empty if ((FieldConstants.CREATE_TIME) == null) { (metaObject, FieldConstants.CREATE_TIME, , ()); } if ((FieldConstants.UPDATE_TIME) == null) { (metaObject, FieldConstants.UPDATE_TIME, , ()); } }
In this way, developers can effectively reduce unnecessary field fill operations, especially in high concurrency environments, where this optimization improves performance.
8.3 Using batch operations
When processing large amounts of data, inserting or updating one by one is often inefficient, especially in scenarios where each record needs to be automatically filled. In order to improve the overall performance of the system, developers should try to use batch operations, which can not only reduce the overhead of database connections, but also greatly improve the efficiency of data processing.
8.3.1 MyBatis-Plus batch operation support
MyBatis-Plus provides good support for batch insertion and batch updates, which developers can callinsertBatch
orupdateBatch
Method to implement batch operations. These batch operation methods perform database operations through batch SQL statements at the bottom, greatly reducing the number of database interactions.
8.3.2 Combining batch operations with MetaObjectHandler
When using batch operations,MetaObjectHandler
It can still work by automatically filling batch data, so as to ensure that every record in batch operations can complete the filling process correctly.
@Override public void insertBatch(List<YourEntity> entityList) { for (YourEntity entity : entityList) { MetaObject metaObject = (entity); insertFill(metaObject); } (entityList); }
Through batch operations, developers can significantly improve performance when processing large amounts of data, especially when processing millions of data, the advantages of batch operations are particularly obvious.
9. Frequently Asked Questions and Solutions
In useMetaObjectHandler
During the process, you may encounter some common problems, which may affect the effect of automatic filling and even cause system errors. Understanding the causes of these problems and mastering corresponding solutions can help developers better apply.MetaObjectHandler
。
9.1 Field fill failed
9.1.1 Cause Analysis
Field fill failure isMetaObjectHandler
A common problem during use is usually because the field name does not match the attribute name in the entity class, or the field type is incorrect. becauseMetaObjectHandler
Rely on the reflection mechanism to fill fields, so matching field names and types is particularly important.
9.1.2 Solution
The developer should ensureMetaObjectHandler
The field name specified in is exactly the same as the attribute name in the entity class, and it is also necessary to ensure that the field type matches the field type in the database. In addition, use compile-time checking tools (e.g.Lombok
of@Data
Annotation) The generated getter and setter methods can reduce spelling errors introduced due to manual code writing.
@Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); }
9.2 Data consistency problem in multithreaded environment
9.2.1 Cause analysis
In a multi-threaded environment,MetaObjectHandler
If the fill logic involves shared states (such as global variables or context information), it may cause data consistency problems and even cause undetectable concurrency errors. Since multiple threads may access and modify shared state at the same time, data race occurs, which affects the correctness of field filling.
9.2.2 Solution
Developers can avoid data consistency issues in multi-threaded environments in the following ways:
-
Thread-safe design:make sure
MetaObjectHandler
The implementation is thread-safe to avoid race conditions in multi-threaded environments. It can be done by using thread-local variables (ThreadLocal
) to isolate data from different threads and avoid conflicts in shared states. -
Stateless implementation: Try to keep
MetaObjectHandler
The implementation is designed to be stateless, avoiding the use of any global state or variables that will be shared by multiple threads. Stateless implementations can effectively prevent data consistency problems during concurrent access.
private ThreadLocal<LocalDateTime> currentTime = (LocalDateTime::now); @Override public void insertFill(MetaObject metaObject) { (metaObject, FieldConstants.CREATE_TIME, , ()); }
Through the above methods, data consistency problems in multi-threaded environments can be effectively avoided and ensured thatMetaObjectHandler
Correctness and stability in a concurrent environment.
9.3 Performance Bottleneck
9.3.1 Cause Analysis
If the fill logic in `MetaObjectHandler` is designed too complex or executes too long, it can become a performance bottleneck for the system, especially when handling large amounts of data or highly concurrent requests. In this case, complex fill logic may cause a significant increase in the response time of the system, which in turn affects the overall performance.
9.3.2 Solution
Developers can optimize in the following waysMetaObjectHandler
Performance:
- Simplify fill logic: Try to avoid performing complex calculations or time-consuming operations in the fill logic, such as database queries, remote calls, etc. These operations can be completed in advance, cached results, and cached results directly when filling.
-
Optimization algorithm:exist
MetaObjectHandler
Use efficient data structures and algorithms to reduce unnecessary time overhead. For example, useHashMap
ReplacementList
Perform searches, or reduce the number of interactions in the database through batch operations.
@Override public void insertFill(MetaObject metaObject) { // Use cached results to avoid repeated queries LocalDateTime cachedTime = getCachedTime(); (metaObject, FieldConstants.CREATE_TIME, , cachedTime); } private LocalDateTime getCachedTime() { // Cache or early calculation results return (); }
Through these optimization methods, developers can significantly improve.MetaObjectHandler
The execution efficiency of avoids becoming a performance bottleneck in the system.
10. Summary
MetaObjectHandler
It is a powerful interface provided by MyBatis-Plus, allowing developers to automatically fill in common fields during insertion and update operations, thereby reducing code duplication and improving development efficiency. However, in high concurrency scenarios, developers need to pay special attention to their performance optimization and thread safety to avoid potential performance bottlenecks and data consistency issues.
10.1 Review of key points
-
MetaObjectHandler
It provides the ability to automatically fill fields when inserting and updating operations. By rationally using cache, reducing unnecessary field fills, and batch operations, performance can be significantly improved. - cache
TableInfo
Information is optimizationMetaObjectHandler
An effective method of performance can reduce unnecessary search overhead. - In a multi-threaded environment, ensure
MetaObjectHandler
Thread safety is crucial, and data consistency issues can be avoided by using thread-local variables and stateless design. - Simplified fill logic and optimization algorithms can be effectively avoided
MetaObjectHandler
It becomes a performance bottleneck of the system, thereby maintaining the efficient operation of the system in a high-concurrency environment.
Through these strategies, developers can make the most of their profitsMetaObjectHandler
Provides flexibility and functionality while ensuring system performance and stability.
10.2 Use fill in combination with annotations
MyBatis-Plus'MetaObjectHandler
and@TableField
Use annotations in conjunction with the automatic filling of fields by labeling fill policies on entity class fields.@TableField
Providedfill
Properties, specify the time for filling fields, such as automatically filling when inserting operations, or automatically updating when updating operations.
Use @TableField
@TableField
The annotationfill
The attribute allows specifying the situation in which the field triggers the automatic fill function. Common fill strategies include:
-
: Automatically fill fields when performing insert operations.
-
FieldFill.INSERT_UPDATE
: Automatically fill fields when performing insert or update operations.
Through this configuration, it is possible to automatically generate the creation time when data is inserted, and automatically update the modification time when data is updated.
Example
Suppose there is an entity classUser
,increateTime
Fields need to be automatically filled when inserted.updateTime
Fields need to be automatically updated when inserting and updating:
import ; import ; public class User { private Long id; @TableField(fill = ) private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; // getters and setters }
This is the article about the principles and use of MyBatis-Plus MetaObjectHandler. For more information about MyBatis-Plus MetaObjectHandler, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!