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

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

相关推荐
Code哈哈笑4 小时前
【Spring Boot】深入解析:#{} 和 ${}
java·spring boot·后端·spring·mybatis
quququ_21386 小时前
Java面试:从Spring Boot到微服务的全面考核
spring boot·微服务·kubernetes·mybatis·hibernate·java面试
BillKu15 小时前
Spring Boot + MyBatis 动态字段更新方法
java·spring boot·mybatis
我家领养了个白胖胖1 天前
#和$符号使用场景 注意事项
java·后端·mybatis
论迹1 天前
【JavaEE】-- MyBatis操作数据库(1)
java·开发语言·数据库·java-ee·mybatis
述雾学java1 天前
Mybatis延迟加载、懒加载、二级缓存
mybatis·java核心基础
红豆和绿豆2 天前
mybatis-plus开发orm
java·开发语言·mybatis
Java&Develop2 天前
Spring Boot+Mybatis设置sql日志打印
spring boot·sql·mybatis
安清h2 天前
【基于SprintBoot+Mybatis+Mysql】电脑商城项目之显示勾选的购物车数据和创建订单
数据库·spring boot·后端·mysql·mybatis
Code哈哈笑2 天前
【Spring Boot基础】MyBatis的基础操作:增删查改、列名和属性名匹配 -- XML实现
xml·java·spring boot·后端·spring·mybatis