SoFunction
Updated on 2025-03-08

MyBatis-Plus The specific implementation of optimistic lock

In modern applications,Optimistic lock(Optimistic Locking) is an important mechanism to solve concurrency problems. It ensures consistency of data by verifying the data version when it is updated, thus avoiding concurrent conflicts. Unlike pessimistic locks, optimistic locks do not rely on the database lock mechanism, but rather determine whether the data has been modified by other transactions by checking the version or flag fields of the data.

MyBatis-Plus provides convenient optimism locking support, and the optimistic locking mechanism can be achieved through simple configuration, ensuring data consistency in high concurrency scenarios without affecting the system's concurrency performance.

1. What is optimistic lock

Optimistic lockIt is an implementation of optimistic concurrency control. It assumes that multiple transactions will not conflict when operating data concurrently, or the probability of conflict is low, so resources will not be locked directly at each operation. Its basic idea is to add a version number field to each record of the data to represent the version of the data. When the user updates the data, it checks whether the version number has changed.

A typical workflow for optimistic locks is as follows:

  • When reading data, the version number of the record is read at the same time.
  • When updating data, check whether the version number of the current data is consistent with the time of reading.
    • If the version numbers are the same, it means that the data has not been modified by other transactions. You can perform an update operation and add 1 to the version number.
    • If the version numbers are inconsistent, it means that the data has been modified by other transactions. At this time, updates should be abandoned, prompting the user data has been modified.

2. The implementation of MyBatis-Plus optimistic lock

Optimistic locks in MyBatis-Plus are implemented through the version number field, which usually requires the following steps:

  • Add a version number field to the data in the entity class.
  • Configure the optimistic lock plugin for MyBatis-Plus.
  • The version number is automatically checked by MyBatis-Plus during updates and incremented after successful updates.

3. MyBatis-Plus optimistic lock configuration

1. Introduce dependencies

First, the MyBatis-Plus dependency needs to be introduced into the project. If you have already used MyBatis-Plus, you can skip this step.

<dependency>
    <groupId></groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

2. Configure the optimistic lock plug-in

MyBatis-Plus provides a built-in optimistic lock plug-in that needs to be registered in the project's configuration class:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // Add optimistic lock plugin        (new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

OptimisticLockerInnerInterceptorIt is an optimistic lock plug-in provided by MyBatis-Plus. When we perform update operations, it will automatically check the version number of the data to ensure that the optimistic lock takes effect.

3. Entity configuration

In entity classes, use@VersionAnnotation identifies the version field that optimises lock. The version field type is usuallyIntegerorLong, When updating data, MyBatis-Plus will automatically check and increment the value of this field.

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;

    // Optimistic lock version number field    @Version
    private Integer version;
}

In this example,versionFields are used to record version numbers.@VersionAnnotation tells MyBatis-Plus that this field is an optimistic locked version control field.

4. Update operation

When performing an update operation, MyBatis-Plus automatically checks the version number of the data. If the version number matches, the update is successful and the version number is added by 1; if the version number does not match, the update fails to prevent the data from being overwritten.

User user = (1L); // Read user data("New Name");
(30);

int result = (user);  // Perform updates
if (result == 0) {
    // If the return value is 0, it means that the update failed and the version number does not match    ("Update failed, data may have been modified by other users");
} else {
    // If the update is successful, MyBatis-Plus will automatically add 1 to the version field    ("Update Successfully");
}

MyBatis-Plus automatically generates updates SQL similar to the following SQL:

UPDATE user
SET name = 'New Name', age = 30, version = version + 1
WHERE id = 1 AND version = 1;
  • version = 1Used to ensure that the data is not modified by other transactions when updated.
  • version = version + 1After the update is successful, the version number is automatically incremented.

4. The working principle of optimistic locking

MyBatis-Plus' optimistic lock passes@VersionAnnotation and optimistic lock plug-in implementation. When we update the data, MyBatis-Plus will add a conditional check on the version number to the generated SQL statement. If the version number matches, the update will be successful and the version number will be added by 1; if the version number does not match, it means that the data has been modified by other transactions and the update operation will fail.

Specifically, the optimistic lock of MyBatis-Plus will perform the following steps:

  • Query data: First, the user reads the data and reads the version number of the data at the same time.
  • Modify data: The user modifys the data content, and does not modify the version number field.
  • Submit update: When the user submits an update, MyBatis-Plus will be inWHERECheck the version number in the condition.
    • If the version number matches, the update is successful and the version number is increased by 1.
    • If the version number does not match and the update fails, MyBatis-Plus returns 0, indicating that the update is not successful.

5. Optimistic lock failure handling

When using optimistic locks for concurrency control, update failures may occur, usually because the data has been modified by other users before the user submits the modification. In this case, it needs to be processed according to the business scenario, and common processing methods include:

  • Prompt the user to re-get the latest data: After the update fails, the user's data has been prompted to be changed, so that the user can re-view and modify it.
  • Automatic retry mechanism: When the update fails, the system can try to re-read the latest data and re-execute the update operation within a certain number of times.
  • Merge data: In some cases, you can try to merge user modifications with the latest data in the database to avoid data loss.

Here is a simple example of the automatic retry mechanism:

int retryCount = 3;  // Maximum number of retryboolean success = false;

while (retryCount &gt; 0 &amp;&amp; !success) {
    User user = (1L);  //Reread the data    ("New Name");
    (30);

    int result = (user);  // Try to update
    if (result == 0) {
        retryCount--;
        ("Update failed, remaining retry times:" + retryCount);
    } else {
        success = true;
        ("Update Successfully");
    }
}

if (!success) {
    ("Update failed, please try again");
}

In this example, the system will automatically retry when the update fails until the maximum number of retries is reached.

6. Optimistic lock application scenarios

Optimistic locks are suitable for the following application scenarios:

  • High concurrency environment: In high concurrency scenarios, optimistic locking can reduce the time of database locking and improve the system's concurrency performance. Especially in scenarios where more reads and less writes, optimistic locking can avoid frequent lock operations well.
  • Stateless Service: Optimistic locking is suitable for stateless services, especially in distributed systems. Since optimistic locking does not rely on the database lock mechanism, it is suitable for distributed transaction scenarios.
  • Business allows for retry failure: Optimistic locking ensures data consistency and provides a simple way to handle failures when business logic allows users to retry.

7. Pros and cons of MyBatis-Plus Optimistic Lock

advantage:

  • Improve concurrency performance: Optimistic locking does not require database-level locking, avoids long-term use of resources, and is suitable for high-concurrency environments.
  • Avoid deadlocks: Since optimistic locking does not have a database lock operation, the problem of deadlocking in concurrent operations is avoided.
  • Non-invasive: MyBatis-Plus' optimistic lock is implemented through annotations and plugins, which is very little invasive to existing code.

shortcoming:

  • High possibility of update failure: In scenarios where there are many concurrent write operations, optimistic locking may lead to a high update failure rate, and a retry mechanism is needed to ensure data modification.
  • Limited applicable scenarios: Optimistic lock is more suitable for business scenarios where more reads, less writes, and if the write operations are frequent, it may lead to frequent update failures.

8. Summary

MyBatis-Plus' optimistic lock can easily achieve data concurrency control in high concurrency scenarios through simple configuration and annotation. Through the version number mechanism, MyBatis-Plus ensures that data will not be overwritten by mistake when multiple users operate data simultaneously. At the same time, the optimistic locking mechanism does not rely on the database locking mechanism and is suitable for stateless, distributed systems and high-concurrency environments.

This is the end of this article about the specific implementation of MyBatis-Plus optimistic lock. For more related content of MyBatis-Plus optimistic lock, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!