详解MybatisPlus中@Version注解的使用

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

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

标签:MybatisPlus,@Version,注解
0
投稿

猜你喜欢

  • Spring Boot提高开发效率必备工具lombok使用

    2022-05-21 08:22:38
  • 关于Mybatis-Plus字段策略与数据库自动更新时间的一些问题

    2023-08-05 20:44:22
  • C#如何防止程序多次运行的技巧

    2022-11-10 01:18:59
  • Java判断ip是否为IPV4或IPV6地址的多种方式

    2023-03-28 01:18:31
  • JavaWeb如何实现禁用浏览器缓存

    2021-09-13 01:27:45
  • 浅谈Java堆外内存之突破JVM枷锁

    2022-10-19 19:46:50
  • C#11新特性使用案例详解

    2023-11-26 03:19:15
  • 详解spring boot集成RabbitMQ

    2022-06-25 17:56:07
  • C#中+=是什么意思及+=的用法

    2023-07-11 23:25:31
  • 深入分析Java内存区域的使用详解

    2023-09-25 23:21:29
  • Android中为activity创建菜单

    2022-10-19 05:52:12
  • android仿微信联系人索引列表功能

    2023-06-22 17:33:30
  • SpringBoot详细讲解静态资源导入的实现

    2023-07-26 13:23:21
  • 详解Java的Hibernat框架中的Map映射与SortedMap映射

    2021-08-21 20:31:59
  • Springboot 整合shiro实现权限控制的方法

    2021-09-21 20:15:47
  • java多线程读取多个文件的方法

    2022-12-05 04:37:45
  • Java String的intern用法解析

    2023-04-22 19:03:35
  • Java的接口和抽象类深入理解

    2023-01-26 02:19:22
  • 详解Android消息机制完整的执行流程

    2021-10-14 18:11:00
  • c# 剔除sql语句'尾巴'的五种方法

    2022-09-20 16:32:39
  • asp之家 软件编程 m.aspxhome.com