2.樂觀鎖,悲觀鎖
阿新 • • 發佈:2021-06-24
在資料庫中新增樂觀鎖欄位
在pojo類的屬性上增加註解
//樂觀鎖的註解 @Version private Integer version;
mybatis-plus的配置類,之前在主入口配置的mapper可以移植到此處
@MapperScan("com.wu.mapper") @EnableTransactionManagement//開啟事務 @Configuration//配置類 public class MybatisPlusConfig { //註冊樂觀鎖的外掛 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){return new OptimisticLockerInterceptor(); } }
測試樂觀鎖成功
//測試樂觀鎖成功 @Test public void testOptimisticLocker(){ //查詢使用者資訊 User user=userMapper.selectById(1L); //修改使用者資訊 user.setName("小吳"); userMapper.updateById(user); }
JDBC Connection [HikariProxyConnection@1038002783 wrapping com.mysql.cj.jdbc.ConnectionImpl@4667c4c1] will not be managed by Spring==> Preparing: UPDATE user SET name=?, age=?, email=?, version=?, create_time=?, update_time=? WHERE id=? AND version=? ==> Parameters: 小吳(String), 1(Integer), [email protected](String), 2(Integer), 2021-06-25 05:18:23.0(Timestamp), 2021-06-25 05:18:23.0(Timestamp), 1(Long), 1(Integer) <== Updates: 1
測試樂觀鎖失敗
//測試樂觀鎖失敗 @Test public void testOptimisticLocker2(){ //查詢使用者資訊 User user=userMapper.selectById(1L); //修改使用者資訊 user.setName("小吳1"); //查詢使用者資訊 User user2=userMapper.selectById(1L); //修改使用者資訊 user2.setName("小吳2"); //小吳2插隊 userMapper.updateById(user2); userMapper.updateById(user);//如果沒有樂觀鎖就會覆蓋插隊執行緒的值 }
結果是小吳2插隊成功