1. 程式人生 > 程式設計 >mybatis-plus樂觀鎖實現方式詳解

mybatis-plus樂觀鎖實現方式詳解

悲觀鎖、樂觀鎖簡介:

悲觀鎖:同步操作。即使用者A在操作某條資料時,為其上鎖,限制其他使用者操作,使用者A操作完成提交事務後其他使用者方可操作此資料。

樂觀鎖:使用版本控制欄位。更新某條資料時,先判斷此資料的version是否符合條件,若符合則更新反之更新失敗。

mybatis-plus樂觀鎖實現方式

1.向資料庫中新增版本控制欄位version

ALTER TABLE `user` ADD COLUMN `version` INT

2.實體類中對應此欄位新增@Version註解

mybatis-plus樂觀鎖實現方式詳解

特別說明:

特別說明:

  • 支援的資料型別只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整數型別下 newVersion = oldVersion + 1
  • newVersion 會回寫到 entity 中
  • 僅支援 updateById(id) 與 update(entity,wrapper) 方法
  • 在 update(entity,wrapper) 方法下,wrapper 不能複用!!!

3.寫個配置類,註冊樂觀鎖外掛

@Configuration
@MapperScan("com.atguigu.mybatis_plus.mapper")
public class MybatisPlusConfig {
/**
* 樂觀鎖外掛
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
 }
}

到此這篇關於mybatis-plus樂觀鎖實現方式的文章就介紹到這了,更多相關mybatis-plus樂觀鎖內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!