软件编程
位置:首页>> 软件编程>> java编程>> 详解MybatisPlus中@Version注解的使用

详解MybatisPlus中@Version注解的使用

作者:知识的搬运工旺仔  发布时间:2023-11-09 23:49:17 

标签:MybatisPlus,@Version,注解

1. 简单介绍

嗨,大家好,今天给想给大家分享一下关于Mybatis-plus 的 Service 层的一些方法的使用。今天没有总结,因为都是一些API没有什么可以总结的,直接看着调用就可以了。

下面我们将介绍 @Version 注解的用法,以及每个属性的实际意义和用法

2. 注解说明

在 MyBatis Plus 中,使用 @Version 实现乐观锁,该注解用于字段上面

3. 什么是乐观锁

3.1 乐观锁简介

  • 乐观锁(Optimistic Locking)是相对悲观锁而言的,乐观锁假设数据一般情况下不会造成冲突

  • 所以在数据进行提交更新的时候,才会正式对数据的冲突进行检测

  • 如果发现冲突了,则返回给用户错误的信息,让用户决定如何去做

  • 乐观锁适用于读操作多的场景,这样可以提高程序的吞吐量

3.2 乐观锁实例

存在两个线程 A 和 B,分别从数据库读取数据。执行后,线程 A 和 线程 B 的 version 均等于 1。如下图

详解MybatisPlus中@Version注解的使用

线程 A 处理完业务,提交数据。此时,数据库中该记录的 version 为 2。如下图:

详解MybatisPlus中@Version注解的使用

线程 B 也处理完业务了,提交数据。此时,数据库中的 version 已经等于 2,而线程的 version 还是 1。程序给出错误信息,不允许线程 B 操作数据。如下图:

详解MybatisPlus中@Version注解的使用

  • 乐观锁机制采取了更加宽松的加锁机制

  • 乐观锁是相对悲观锁而言,也是为了避免数据库幻读、业务处理时间过长等原因引起数据处理错误的一种机制

  • 但乐观锁不会刻意使用数据库本身的锁机制,而是依据数据本身来保证数据的正确性

4. 实例代码

本实例将在前面用到的 user 表上面进行。在进行之前,现在 user 表中添加 version 字段

ALTER TABLE `user`
ADD COLUMN `version`  int UNSIGNED NULL COMMENT '版本信息';

:::info

定义 user 表的 JavaBean,代码如下:

import com.baomidou.mybatisplus.annotation.*;

@TableName(value = "user")
public class AnnotationUser5Bean {
  @TableId(value = "user_id", type = IdType.AUTO)
  private String userId;

@TableField("name")
  private String name;

@TableField("sex")
  private String sex;

@TableField("age")
  private Integer age;

@Version
  private int version;
  // 忽略 getter 和 setter 方法
}

添加 MyBatis Plus 的乐观锁插件,该插件会自动帮我们将 version 加一操作

注意,这里和分页操作一样,需要进行配置,如果不配置,@Version是不会生效的

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

@Bean
   public MybatisPlusInterceptor paginationInterceptor() {
       MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
       // 乐观锁插件
       interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
       return interceptor;
   }

}

测试乐观锁代码,我们创建两个线程 A 和 B 分别去修改用户ID为 1 的用户年龄,然后观察年龄和version字段的值

package com.hxstrive.mybatis_plus.simple_mapper.annotation;

import com.hxstrive.mybatis_plus.mapper.AnnotationUser5Mapper;
import com.hxstrive.mybatis_plus.model.AnnotationUser5Bean;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;

@RunWith(SpringRunner.class)
@SpringBootTest
class AnnotationDemo5 {

@Autowired
   private AnnotationUser5Mapper userMapper;

@Test
   void contextLoads() throws Exception {
       // 重置数据
       AnnotationUser5Bean user5Bean = new AnnotationUser5Bean();
       user5Bean.setUserId(1);
       user5Bean.setAge(0);
       user5Bean.setVersion(0);
       userMapper.updateById(user5Bean);

// 修改数据
       for (int i = 0; i < 10; i++) {
           System.out.println("第 " + (i + 1) + " 次修改数据");
           final CountDownLatch countDownLatch = new CountDownLatch(2);
           modifyUser(countDownLatch, "My-Thread-A", 1);
           modifyUser(countDownLatch, "My-Thread-B", 1);
           countDownLatch.await();
           Thread.sleep(100L);
       }
   }

private void modifyUser(final CountDownLatch countDownLatch, String threadName, int userId) {
       Thread t = new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   String threadName = Thread.currentThread().getName();
                   try {
                       AnnotationUser5Bean userBean = userMapper.selectById(userId);
                       if (null == userBean) {
                           return;
                       }
                       AnnotationUser5Bean newBean = new AnnotationUser5Bean();
                       newBean.setName(userBean.getName());
                       newBean.setSex(userBean.getSex());
                       newBean.setAge(userBean.getAge() + 1);
                       newBean.setUserId(userBean.getUserId());
                       newBean.setVersion(userBean.getVersion());
                       int result = userMapper.updateById(newBean);
                       System.out.println("result=" + result + " ==> " + userBean);
                   } catch (Exception e) {
                       System.err.println(threadName + " " + e.getMessage());
                   }
               } finally {
                   countDownLatch.countDown();
               }
           }
       });
       t.setName(threadName);
       t.start();
   }

}

在运行上面代码之前,我们数据库中的记录值如下:

user_idnamesexageversion
1测试00

运行上面程序,数据库记录如下:

user_idnamesexageversion
1测试016

1.上面代码将执行10次循环操作,每次操作启动两个线程(线程 A 和 线程 B)去修改用户数据。

2.如果数据没有任何冲突,则用户的年龄应该是 20。但是上面程序运行完成后年龄为 16

3.这就说明,在线程运行的时候,可能A 刚好修改了version,并没有执行完,就到B线程了,就导致B线程修改失败

来源:https://blog.csdn.net/weixin_46213083/article/details/125318776

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com