Mybatis-Plus乐观锁配置使用流程【OptimisticLockerInnerInterceptor】

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家:++人工智能学习网站++

1.乐观锁实现

1.配置插件

1.XML方式

xml 复制代码
<bean class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor" id="optimisticLockerInnerInterceptor"/>

<bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
    <property name="interceptors">
        <list>
            <ref bean="optimisticLockerInnerInterceptor"/>
        </list>
    </property>
</bean>

2.Springboot注解方式

下方为博主使用时场景 单独写config带@Bean注解

java 复制代码
private MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mpi = new MybatisPlusInterceptor();
        //添加乐观锁拦截器
        mpi.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mpi;
    }

单独写config文件如下:

java 复制代码
// Spring Boot 方式
@Configuration
@MapperScan("按需修改")
public class MybatisPlusConfig {
    /**
     * 旧版
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 新版
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

2.实体类字段增加注解

java 复制代码
@Version
private Integer versionNumber;

注意:支持的数据类型有int,Integer,long,Long,Date,Timestamp,LocalDateTime并且仅支持 updateById(id) 与 update(entity, wrapper) 方法在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

2.Parameter 'MP_OPTLOCK_VERSION_ORIGINAL' not found. Available parameters are param1, et问题解决

本身乐观锁使用比较简单 但是遇到了乐观锁插件注入失败问题 网上解决思路如下:

1、先在数据库表中添加version字段

2、在实体类中定义version字段,并使用@Version注解标记

3、在mybatis-plus拦截器中添加OptimisticLockerInnerInterceptor()乐观锁拦截器

但是并未解决我的问题 随后查看项目 发现项目中已经创建了一个sqlSessionFactory:

本身mybatisplus在启动项目时会自动扫描并注入相关插件 但是此处单独配置后 并且添加了@Primary注解 后续就只会走此处的配置 所以我们在外部添加的添加乐观锁插件实际并未真正添加成功 或者说并没有走我们添加乐观锁插件的代码 解决如下:

还有一种思路就是 启动类禁用掉之前配置 那我们单独写的添加乐观锁配置类也可以生效~

相关推荐
paopaokaka_luck14 小时前
基于springboot+vue的智慧家政管理系统(AI问答、 WebSocket实时沟通、ECharts运营分析、订单规则与服务追踪)
java·javascript·spring boot·数据分析·echarts·mybatis
大牧师18 小时前
Mybatis 框架教程
java·数据库·mybatis·数据持久化·orm
代码什么用1 天前
MyBatis使用PageHelper && MyBatis的注解式开发
mybatis
VX_bysjlw9851 天前
数码设备销售网站设计与实现39138-计算机毕设原创(免费领源码+带部署教程)
java·vue.js·spring boot·mysql·tomcat·mybatis·idea
天空鸟_时光不老2 天前
13-亮点提炼:把技术说辞翻译成业务价值
java·spring boot·spring·spring cloud·mybatis
CSharp精选营2 天前
两个请求同时改库存,RowVersion 救了一命
乐观锁·efcore·并发控制·库存超卖·rowversion
禾小西3 天前
Redis AOF 日志:宕机了,如何避免数据丢失?
java·redis·mybatis
天空鸟_时光不老3 天前
09-RAG问答系统落地:从默认分割器的坑到Milvus召回调优
java·人工智能·spring boot·spring·spring cloud·maven·mybatis
西凉的悲伤3 天前
MyBatis 中 association 与 collection 详解
java·mybatis
天空鸟_时光不老3 天前
10-Agent安全隐患与SQL执行层加固
java·数据库·人工智能·sql·spring·maven·mybatis