mybatis-plus 乐观锁
作用:保护数据安全,多线程下加锁
过程:
1、先查询,获取当前的版本号
2、若版本号,不对则更新失败
使用
1、在数据库中添加version 字段
2、实现类
package com.wt.pojo; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; @Version private Integer version; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; }
3、新建配置类
package com.wt.config; import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @MapperScan("com.wt.mapper") @EnableTransactionManagement // @Configuration // 配置类 public class MyBatisPlusConfig {
@Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); } }
4、测试
@Test // 乐观锁,模拟多线程, user1 更新失败, user2 更新成功 public void testVersionLock(){ // 1. 查询用户信息 User user1 = userMapper.selectById(1); // 2.修改用户信息 user1.setId(1L); user1.setName("ajax1"); User user2 = userMapper.selectById(1); user2.setId(1L); user2.setName("ajax22"); userMapper.updateById(user2); userMapper.updateById(user1); }