乐观锁:十分乐观。总是认为不会出现问题,无论干什么也不上锁,出了问题再次更新测试。
悲观锁:十分悲观。总是认为会出问题,无论干什么都会上锁,再去操作。
乐观锁实现方式:
·取出记录时,获取当前version
·更新时带上version
·执行更新时,set version=newVersion where version=oldVersion
·如果version不对,就更新失败
如:
--A update user set name="abc",version=version+1 where id=2 and version =1 --B 比A先完成更新,这时version=2会导致A修改失败 update user set name="abc1",version=version+1 where id=2 and version =1
乐观锁插件:
①给数据库增加version字段
②实体类加对应字段
@Version //乐观锁version注解 private int version;
③注册组件
建一个配置类
package com.example.demo.config; import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; //扫描mapper文件夹 @MapperScan("com.example.demo.mapper") @EnableTransactionManagement//开启事物 @Configuration//配置类 public class MyBatisPlusConfig { //注册乐观锁插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); } }
④测试
成功:
@Test public void testOptimisticLocker(){ //查询用户信息 User user = userMapper.selectById(1); //修改用户 user.setName("abc"); user.setEmail("abc@163.com"); //执行更新操作 userMapper.updateById(user);//UPDATE user SET name=?, age=?, email=?, update_time=?, version=? WHERE id=? AND version=? }
更新前
更新后
失败:
//测试乐观锁失败!多线程 @Test public void testOptimisticLocker2(){ //线程1 User user1 = userMapper.selectById(1); user1.setName("abc2"); user1.setEmail("abc2@163.com"); //线程2 模拟另外一个线程执行了插队操作 User user2 = userMapper.selectById(1); user2.setName("abc1"); user2.setEmail("abc1@163.com"); //执行更新操作 userMapper.updateById(user2); userMapper.updateById(user1); }
更新前:
更新后: