ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何在Mybatis-Plus项目中,使用乐观锁

2021-11-29 15:33:20  阅读:200  来源: 互联网

标签:p2 System 乐观 Plus productMapper Mybatis interceptor getPrice public


一、环境搭建

环境搭建链接

二、表创建

create table product
(
    id      bigint auto_increment comment '主键ID'
        primary key,
    name    varchar(30)   null comment '商品名称',
    price   int default 0 null comment '价格',
    version int default 0 null comment '乐观锁版本号'
);
INSERT INTO product (id, name, price, version) VALUES (1, '笔记本', 100, 0);

三、pojo创建,config文件

pojo创建

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

乐观锁插件导入

@Configuration
@MapperScan("com.study.mybatisplus.mapper")
public class MybatisPlusConfig {

    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //定义一个插件管理器或者连接器的一个概念
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //把分页拦截器创建,配置到interceptor对象里
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

四、代码测试

@Test
    public void testConcurrentUpdate() {
        //1、小李
        Product p1 = productMapper.selectById(1L);
        //2、小王
        Product p2 = productMapper.selectById(1L);
        //3、小李将价格加了50元,存入了数据库
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改结果:" + result1);
        //4、小王将商品减了30元,存入了数据库 乐观锁生效 该代码失效
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改结果:" + result2);

        //解决方案:更新失败,重试
        if(result2 == 0){
            System.out.println("小王重试");
            //重新获取数据
            p2 = productMapper.selectById(1L);
            //更新
            p2.setPrice(p2.getPrice() - 30);
            productMapper.updateById(p2);
        }

        //最后的结果
        Product p3 = productMapper.selectById(1L);
        System.out.println("最后的结果:" + p3.getPrice());
    }

标签:p2,System,乐观,Plus,productMapper,Mybatis,interceptor,getPrice,public
来源: https://blog.csdn.net/weixin_42865375/article/details/121610967

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有