目录
  • 1. 简单介绍
  • 2. 注解说明
  • 3. 什么是乐观锁
    • 3.1 乐观锁简介
    • 3.2 乐观锁实例
  • 4. 实例代码

    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_id name sex age version
    1 测试 0 0

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

    user_id name sex age version
    1 测试 0 16

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

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

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

    以上就是详解MybatisPlus中@Version注解的使用的详细内容,更多关于MybatisPlus @Version注解的资料请关注其它相关文章!

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。