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

相关文章

今天小编给大家分享的是MyBatis批量查询、插入、更新、删除如...
今天小编给大家分享的是Mybatis操作多数据源实现的方法,相信...
本篇文章和大家了解一下mybatis集成到spring的方式有哪些。有...
今天小编给大家分享的是mybatis-plus分页查询的3种方法,相信...
本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感...
这篇文章主要介绍了mybatisforeach怎么传两个参数的相关知识...