“This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

In the operation of relational database management system, the problem of locking is often encountered. There are row locks, page locks and table locks in the database. Pessimistic and optimistic locks are often encountered during Java development. Optimistic and pessimistic locking are critical to understanding Java multithreading, concurrency, and databases. Here we have a chat about Mybatis_Plus optimistic lock.

The database lock

Lock is an important concept in database. In the case of high concurrency of big data, if the same data is read by multiple threads, phantom read, dirty read and misread may occur. So locks were introduced. On the programmer side, pessimistic and optimistic locks can be classified based on their use.

Pessimistic locks assume that the worst will happen. The current data may be modified so that the resource or data will be locked while reading the data. Other threads using the data or resource will block and wait until the pessimistic lock releases the lock.

Optimistic locks are the opposite of pessimistic locks. Optimistic locks always assume that resources and data will not be modified and will not be locked when data and resources are read. However, optimistic locking determines whether the current data and resources have been modified during the write operation. Generally speaking, there are two implementation schemes of optimistic locking: version number mechanism and CAS implementation.

In our project, we use Mybatis_Plus agile development. We recently learned optimistic locking based on Mybatis_Plus. Let’s get started quickly.

Quick start

Version is introduced

This will be based on Spring Boot to build a learning Mybatis_Plus optimistic lock Demo. The development environment is as follows:

JDK18.
SpringBoot 2.3. 0.RELEASE
mybatis-plus 3.3. 0
Copy the code

The realization principle of Mybatis_Plus optimistic lock is controlled based on version number mechanism. After a piece of data is retrieved, the system updates the data and obtains the version version of the current data. During the update, the system checks whether the current version is consistent with the version in the database. Version The version number +1. If the version number is inconsistent, the data has been modified and the data fails to be updated. So with that in mind, let’s start quickly.

Introduction of depend on

The dependency packages used in this study are as follows:

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.4.0</version>
        </dependency>
Copy the code

Configuring Optimistic Locking

The interceptor information for configuring optimistic locks in a project is as follows:

@Component
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        returninterceptor; }}Copy the code

Specify version number

Specify a Version number field in our database entity object and annotate it with the @version annotation. The @version annotation field type supports: Int, Integer, long, long, the Date and Timestamp, LocalDateTime, under the Integer types newVersion = oldVersion + 1 is automatically incremented version number, Note that only updateById() and Update (Entity, Wrapper) methods are supported. Create a User object this time.

@ApiModel(value = "com-example-demo-module-User")
@TableName("user")
public class User {

    @TableId(value = "id", type = IdType.INPUT)
    private Integer id;
    @TableField(value = "name")
    private String name;
    @TableField(value = "age")
    private int age;
    @Version
    private int version;
}
Copy the code

Unit testing

Once you’ve written the basic configuration above, you’re ready for a simple unit test. First we create a user information.

    @Test
    void TestUser(){
        User user = new User();
        user.setName(1 "test");
        user.setAge(12);
        userMapper.insert(user);
    }
Copy the code

You can view that user Test 1 is successfully added and the current user ID is 19.

Write unit test 2, update user information with ID 19 twice this time.

     @Test
    void TestUser(){
        User user = userService.getById(19);
        System.out.println(user);
        // Start updating once
        userService.updateByTest(user);
        user.setName("To test the 32222");
        userService.updateById(user);
        User user1 = userService.getById(user.getId());
        System.out.println("Second updated method:" +user1);
    }
Copy the code

The version number has been automatically updated:

User{id=19, name='test 32222', age=12, version=0} the first updated method: User{id=19, name='123456', age=12, version=1} The second update method: User{id=19, name='test 32222', age=12, version=2}
Copy the code

conclusion

Well, the above is Spring Boot integration Mybatis_Plus optimistic lock, thank you for reading, I hope you like, if you help, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.