柚子快報(bào)邀請(qǐng)碼778899分享:MybatisPlus(5)
柚子快報(bào)邀請(qǐng)碼778899分享:MybatisPlus(5)
前言??
??????SSM專欄更新中,各位大佬覺得寫得不錯(cuò),支持一下,感謝了!??????
Spring + Spring MVC + MyBatis_冷兮雪的博客-CSDN博客
上篇講了增刪的操作,這篇講修改操作中的一個(gè)問題以及它對(duì)應(yīng)的解決方案——樂觀鎖,還有代碼生成器的實(shí)現(xiàn)。
一、樂觀鎖(update)??
業(yè)務(wù)并發(fā)現(xiàn)象帶來的問題: 秒殺。
我們應(yīng)該都遇過買東西限量秒殺吧,這個(gè)時(shí)候這么多人一起搶,我們應(yīng)該怎么去實(shí)現(xiàn)秒殺程序呢?
下面我們會(huì)講解2000訪問量的秒殺實(shí)現(xiàn),如果是更多人的話就應(yīng)該使用其他更好的方法了。
1、添加字段和實(shí)體類屬性??
添加version字段,默認(rèn)值為1
?實(shí)體類屬性也添加應(yīng)該version屬性:
package com.example.domain;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@Data
/*@TableName("tbl_user")*/
public class User {
@TableId(type= IdType.ASSIGN_ID)
private Long id;
private String name;
@TableField(value = "pwd",select = false)
private String password;
private Integer age;
private String tel;
/*@TableLogic(value = "0",delval = "1")*/
private Integer deleted;
@Version
private Integer version;
@TableField(exist = false)
private Integer online;
}
?2、@Version原理??
當(dāng)人人去進(jìn)行秒殺時(shí),成功搶到商品的用戶,會(huì)更新用戶的version值,
update set_abc=1,version = version + 1 where version=1
如上面這個(gè)SQL一樣。當(dāng)一個(gè)僅剩的一個(gè)商品被搶走,這個(gè)version值就會(huì)變化,其他人就會(huì)顯示搶不到商品。
添加樂觀鎖攔截器(和分頁功能一樣)??
使用這個(gè)和分頁功能一樣,需要添加攔截器:
package com.example.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mpInterceptor(){
//1.定義Mp攔截器
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
//2.添加具體的攔截器
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
//3、添加樂觀鎖攔截器
mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mpInterceptor;
}
}
3、測(cè)試代碼??
我們?nèi)バ薷挠脩鬷d=2的用戶名:
@Test
void testUpdate(){
User user=new User();
user.setId(2L);
user.setName("編程");
userDao.updateById(user);
}
運(yùn)行發(fā)現(xiàn),version值并沒有發(fā)生改變:
柚子快報(bào)邀請(qǐng)碼778899分享:MybatisPlus(5)
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。