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注解 后续就只会走此处的配置 所以我们在外部添加的添加乐观锁插件实际并未真正添加成功 或者说并没有走我们添加乐观锁插件的代码 解决如下:

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

相关推荐
哈喽姥爷1 天前
Spring Boot--yml配置信息书写和获取
java·数据库·spring boot·mybatis
奔跑你个Run2 天前
mybatis plus 使用wrapper输出SQL
mybatis
躲在云朵里`3 天前
Spring Scheduler定时任务实战:从零掌握任务调度
java·数据库·mybatis
Java小白程序员4 天前
MyBatis基础到高级实践:全方位指南(中)
数据库·mybatis
山楂树下懒猴子4 天前
ChatAI项目-ChatGPT-SDK组件工程
人工智能·chatgpt·junit·https·log4j·intellij-idea·mybatis
Mr_hwt_1234 天前
基于mybatis-plus动态数据源实现mysql集群读写分离和从库负载均衡教程(详细案例)
数据库·spring boot·mysql·mybatis·mysql集群
Z_z在努力5 天前
【杂类】Spring 自动装配原理
java·spring·mybatis
little_xianzhong5 天前
关于对逾期提醒的定时任务~改进完善
java·数据库·spring boot·spring·mybatis
MadPrinter5 天前
SpringBoot学习日记 Day11:博客系统核心功能深度开发
java·spring boot·后端·学习·spring·mybatis
奔跑吧邓邓子5 天前
【Java实战㉟】Spring Boot与MyBatis:数据库交互的进阶之旅
java·spring boot·实战·mybatis·数据库交互