99re热视频这里只精品,久久久天堂国产精品女人,国产av一区二区三区,久久久精品成人免费看片,99久久精品免费看国产一区二区三区

MyBatis-Plus 插件-樂觀鎖插件

2022-03-25 14:35 更新

OptimisticLockerInnerInterceptor

當(dāng)要更新一條記錄的時候,希望這條記錄沒有被別人更新

樂觀鎖實現(xiàn)方式:

  • 取出記錄時,獲取當(dāng)前 ?version ?
  • 更新時,帶上這個 ?version ?
  • 執(zhí)行更新時, ?set version = newVersion where version = oldVersion ?
  • 如果 ?version不對,就更新失敗

樂觀鎖配置需要兩步

1、配置插件

  • spring 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>

  • spring boot 注解方式:

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    return interceptor;
}

2、在實體類的字段上加上@Version注解

@Version
private Integer version;

說明:

  • 支持的數(shù)據(jù)類型只有:?int,?Integer,?long?,?Long?,?Date?,?Timestamp?,?LocalDateTime ?
  • 整數(shù)類型下 ?newVersion = oldVersion + 1 ?
  • ?newVersion會回寫到 ?entity
  • 僅支持 ?updateById(id)? 與 ?update(entity, wrapper)? 方法
  • 在 ?update(entity, wrapper)? 方法下, ?wrapper不能復(fù)用!!!

示例:

// 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;
    }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號