MyBatisPlus的乐观锁和悲观锁

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: MyBatisPlus的乐观锁和悲观锁

1.乐观锁

**作用:**当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁的实现方式:

取出记录时,获取当前 version 更新时,带上这个 version 执行更新时, set version = newVersion

where version = oldVersion 如果 version 不对,就更新失败

1.1 场景

  • 一件商品,成本价是80元,售价是100元。老板先是通知小李,说你去把商品价格增加50元。小李正在玩游戏,耽搁了一个小时。正好一个小时后,老板觉得商品价格增加到150元,价格太高,可能会影响销量。又通知小王,你把商品价格降低30元。
  • 此时,小李和小王同时操作商品后台系统。小李操作的时候,系统先取出商品价格100元;小王也在操作,取出的商品价格也是100元。小李将价格加了50元,并将100+50=150元存入了数据库;小王将商品减了30元,并将100-30=70元存入了数据库。是的,如果没有锁,小李的操作就完全被小王的覆盖了。
  • 现在商品价格是70元,比成本价低10元。几分钟后,这个商品很快出售了1千多件商品,老板亏1万多。

理解:同时操作的数据会使数据覆盖;

2.0 乐观锁与悲观锁

  • 上面的故事,如果是乐观锁,小王保存价格前,会检查下价格是否被人修改过了。如果被修改过了,则重新取出的被修改后的价格,150元,这样他会将120元存入数据库。
  • 如果是悲观锁,小李取出数据后,小王只能等小李操作完之后(有一个操作的时候另一人操作会被阻塞也就是无法操作),才能对价格进行操作,也会保证最终的价格是120元。(也就是说你先弄 你弄完之后我才能弄;也就不会导致上面的问题)

3.0 模拟修改冲突

数据库中增加商品表

CREATE TABLE t_product ( 
    id BIGINT(20) NOT NULL COMMENT '主键ID', 
    NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名称', 
    price INT(11) DEFAULT 0 COMMENT '价格', 
    VERSION INT(11) DEFAULT 0 COMMENT '乐观锁版本号', 
    PRIMARY KEY (id) 
);

添加一条数据

INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);

添加一个实体类Product

@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;
    private Integer version;
}

添加一个Mapper接口ProductMapper

package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pojo.Product;
public interface ProductMapper extends BaseMapper<Product> {
}

Demo

按照上面的说明我们来模拟场景进行测试;

@Test
    public void  testProduct01(){
        //1.小李获取商品价格
        Product productLi = productMapper.selectById(1);
        System.out.println("小李获取的商品价格为:" + productLi.getPrice());
        //2.小王获取商品价格
        Product productWang = productMapper.selectById(1);
        System.out.println("小王获取的商品价格为:" + productWang.getPrice());
        //3.小李修改商品价格+50
        productLi.setPrice(productLi.getPrice()+50);
        productMapper.updateById(productLi);
        //4.小王修改商品价格-30
        productWang.setPrice(productWang.getPrice()-30);
        productMapper.updateById(productWang);
        //5.老板查询商品价格
        Product productBoss = productMapper.selectById(1);
        System.out.println("老板获取的商品价格为:" + productBoss.getPrice());
    }

我们一起来看下执行的过程:

执行结果展示

JDBC Connection [HikariProxyConnection@421632334 wrapping com.mysql.cj.jdbc.ConnectionImpl@43c87306] will not be managed by Spring
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 100, 0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4487c0c2]
小李获取的商品价格为:100
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3b705be7] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@981012032 wrapping com.mysql.cj.jdbc.ConnectionImpl@43c87306] will not be managed by Spring
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 100, 0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3b705be7]
小王获取的商品价格为:100
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63d5874f] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@796851467 wrapping com.mysql.cj.jdbc.ConnectionImpl@43c87306] will not be managed by Spring
==>  Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=?
==> Parameters: 外星人笔记本(String), 150(Integer), 0(Integer), 1(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@63d5874f]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8cc8cdb] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@505635448 wrapping com.mysql.cj.jdbc.ConnectionImpl@43c87306] will not be managed by Spring
==>  Preparing: UPDATE t_product SET name=?, price=?, version=? WHERE id=?
==> Parameters: 外星人笔记本(String), 70(Integer), 0(Integer), 1(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8cc8cdb]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fc713c9] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1929506494 wrapping com.mysql.cj.jdbc.ConnectionImpl@43c87306] will not be managed by Spring
==>  Preparing: SELECT id,name,price,version FROM t_product WHERE id=?
==> Parameters: 1(Integer)
<==    Columns: id, name, price, version
<==        Row: 1, 外星人笔记本, 70, 0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fc713c9]
老板获取的商品价格为:70

4.0 通过乐观锁观念解决问题

实体类version字段添加注解@Version

private Long id;
        private String name;
        private Integer price;
        @Version //表示乐观锁版本号字段
        private Integer version;

package com.example.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//地址指向mappe层 持久层也就是Dao接口
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //调用的mybatis的分页拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //我们在此选择数据库的类型,也有其他的参数 我这边选择的mysql
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

添加之后我再次进行测试查看测试的结果(test代码不变)

@Autowired
     private ProductMapper productMapper;
    @Test
    public void  testProduct01(){
        //1.小李获取商品价格
        Product productLi = productMapper.selectById(1);
        System.out.println("小李获取的商品价格为:" + productLi.getPrice());
        //2.小王获取商品价格
        Product productWang = productMapper.selectById(1);
        System.out.println("小王获取的商品价格为:" + productWang.getPrice());
        //3.小李修改商品价格+50
        productLi.setPrice(productLi.getPrice()+50);
        productMapper.updateById(productLi);
        //4.小王修改商品价格-30
        productWang.setPrice(productWang.getPrice()-30);
        productMapper.updateById(productWang);
        //5.老板查询商品价格
        Product productBoss = productMapper.selectById(1);
        System.out.println("老板获取的商品价格为:" + productBoss.getPrice());
    }

查看运行结果:

第一次修改之后就会导致version为2

小李查询商品信息:
 SELECT id,name,price,version FROM t_product WHERE id=?
小王查询商品信息:
 SELECT id,name,price,version FROM t_product WHERE id=?
小李修改商品价格,自动将version+1
 UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
 Parameters: 外星人笔记本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)
小王修改商品价格,此时version已更新,条件不成立,修改失败
 UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
 Parameters: 外星人笔记本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)
最终,小王修改失败,查询价格:150
 SELECT id,name,price,version FROM t_product WHERE id=?

修改测试的代码:

@Test
    public void  testProduct01(){
        //1.小李获取商品价格
        Product productLi = productMapper.selectById(1);
        System.out.println("小李获取的商品价格为:" + productLi.getPrice());
        //2.小王获取商品价格
        Product productWang = productMapper.selectById(1);
        System.out.println("小王获取的商品价格为:" + productWang.getPrice());
        //3.小李修改商品价格+50
        productLi.setPrice(productLi.getPrice()+50);
        productMapper.updateById(productLi);
        int result = productMapper.updateById(productWang);
        if(result == 0){
            //操作失败,重试
            Product productNew = productMapper.selectById(1);
            productNew.setPrice(productNew.getPrice()-30);
            productMapper.updateById(productNew);
        }
        //4.小王修改商品价格-30
        productWang.setPrice(productWang.getPrice()-30);
        productMapper.updateById(productWang);
        //5.老板查询商品价格
        Product productBoss = productMapper.selectById(1);
        System.out.println("老板获取的商品价格为:" + productBoss.getPrice());
    }

我们来看看执行;

结果正常;解决了乐观锁的问题;


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
XML 前端开发 Java
Mybatis-Plus乐观锁配置
Mybatis-Plus乐观锁配置
|
4月前
|
SQL 数据库
MyBatisPlus之逻辑删除、MyBatisPlus解决并发问题的乐观锁机制
MyBatisPlus之逻辑删除、MyBatisPlus解决并发问题的乐观锁机制
70 2
|
4月前
|
数据库
MyBatisPlus-乐观锁概念及实现步骤
MyBatisPlus-乐观锁概念及实现步骤
104 0
|
4月前
|
SQL 存储 算法
Mybatis-Plus- CRUD接口-主键策略-自动填充和乐观锁-分页-逻辑删除-条件构造器和常用接口
Mybatis-Plus- CRUD接口-主键策略-自动填充和乐观锁-分页-逻辑删除-条件构造器和常用接口
|
4月前
|
存储 Java 数据库连接
MyBatis-Plus如何娴熟运用乐观锁
MyBatis-Plus如何娴熟运用乐观锁
214 0
|
4月前
|
Java 关系型数据库 数据库连接
干翻Mybatis源码系列之第十二篇:基于Mybatis Plugins做一个乐观锁
干翻Mybatis源码系列之第十二篇:基于Mybatis Plugins做一个乐观锁
|
9月前
|
XML Java 数据库
mybatis-plus乐观锁
mybatis-plus乐观锁
61 0
|
Java
MyBatisPlus(七)乐观锁
使用乐观锁的意图是:当要更新一条记录的时候,希望这条记录没有被别人更新。那么需要在表中增加一个字段version来实现。
11866 0
|
安全 Java 数据库连接
mybatis plus整合乐观锁
mybatis plus整合乐观锁
|
数据库
springboot+mybatis实现乐观锁
springboot+mybatis实现乐观锁
140 0