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

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

1.乐观锁实现

1.配置插件

1.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注解

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

单独写config文件如下:

// 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.实体类字段增加注解

@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注解 后续就只会走此处的配置 所以我们在外部添加的添加乐观锁插件实际并未真正添加成功 或者说并没有走我们添加乐观锁插件的代码 解决如下:
在这里插入图片描述
在这里插入图片描述
还有一种思路就是 启动类禁用掉之前配置 那我们单独写的添加乐观锁配置类也可以生效~

猜你喜欢

转载自blog.csdn.net/weixin_45735355/article/details/135366100