微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

一、环境搭建

环境搭建链接

二、表创建

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());
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐