MyBatis-Plus樂觀鎖插件的用法小結

什麼是樂觀鎖:

就是我們每一次操作數據後,我們就會更改他的版本號,當另外的線程若想要對該數據進行操作,檢查版本號是否與自己獲得的版本號一致,如果不一致,那麼我們就會取消該操作。

簡介

說明

本文介紹Mybatis-Plus的樂觀鎖插件的用法。

官網網址

樂觀鎖插件 | MyBatis-Plus

配置樂觀鎖插件

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

Entity

版本號的字段上加註解

    @Version
    private Integer version;

說明:

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

測試

MP會把設置進去的版本號當作更新條件,並且版本號+1更新進去。

@Test
public void update(){
	User user = userMapper.getById(1L);
	user.setEmail("[email protected]");
	user.setUpdateTime(LocalDateTime.now());
 
	int update = userMapper.updateById(user);
	System.out.println(update);
}
DEBUG==>  Preparing: UPDATE sys_user SET email=?, update_time=?, version=? WHERE id=? AND version=? 
DEBUG==> Parameters: [email protected](String), 2019-09-19T16:00:38.149(LocalDateTime), 2(Integer), 1(Long), 1(Integer)
DEBUG<==    Updates: 1

到此這篇關於MyBatis-Plus樂觀鎖插件的用法的文章就介紹到這瞭,更多相關MyBatis-Plus樂觀鎖插件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: