乐观锁 主要解决 丢失更新问题
12306抢票问题
多人抢票 只有一人可以得到
第一步
数据库表中添加 version字段
第二步
在User实体类中添加属性并且加上@Version注解
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
自动填充 插入时自带一个version
自动填充参见 Mybatis-Plus字段自动填充_qq_53951760的博客-CSDN博客
this.setFieldValByName("version",1,metaObject);
第三步
自定义乐观锁配置
@Configuration
public class MybatisPlusConfig {
/**
* 新版
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
测试
// 4.乐观锁测试
@Test
public void testOptimisticLocker(){
// 根据id来查询数据
User user = userMapper.selectById(1497827489618153477L);
//修改
user.setAge(222);
//更新
int result = userMapper.updateById(user);
System.out.println("result:"+result);
}
//结果
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@17092fff] will not be managed by Spring
==> Preparing: UPDATE user SET name=?, age=?, email=?, version=?, create_time=?, update_time=? WHERE id=? AND version=?
==> Parameters: lucy2222(String), 222(Integer), 1221@qq.com(String), 2(Integer), 2022-02-27 16:02:49.0(Timestamp), 2022-02-27 16:09:36.023(Timestamp), 1497827489618153477(Long), 1(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@78a515e4]
result:1
结果
数据库表中的version+1