乐观锁:每次不加锁而是假设没有冲突而去完成某项操作,如果失败就重试,直到成功为止
悲观锁:synchronized是独占锁即悲观锁,会导致其他所有需要锁的线程挂起,等待有锁的线程释放锁
乐观锁实现方式:
-
取出记录时,获取当前version
-
更新时,带上这个version
-
执行更新时,set version = newVersion where version = oldVersion
-
如果version不对,就更新失败
update user set name = "wsk",version = version+1
where id = 1 and version = 1
update user set name = "wsk",version = version+1
where id = 1 and version = 1
测试一下Mybatis-Plus乐观锁插件
1、给数据库中增加version字段
![img](https://img-blog.csdnimg.cn/img_convert/0f80094452ff0551af541fa67d7567ec.png)
2、实体类加对应的字段
@Version
private Integer version;
3、注册组件
@MapperScan("com.huang.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
4、测试
public void testOpimisticLocker(){
User user = userMapper.selectById(1L);
user.setAge(18);
user.setEmail("1024955508@qq.com");
userMapper.updateById(user);
}
![img](https://img-blog.csdnimg.cn/img_convert/92774a8bc71cda649fd4a9410c184bf9.png)
![![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VY3ipH45-1634732079213)(MyBatisPlus.assets/I5%5BW9(T)]UQGXA%25RRNED%7D_UG.png](https://img-blog.csdnimg.cn/10cf577ec8f54ea1a04e9a558345a4e8.png))](https://img-blog.csdnimg.cn/fd207a7b375b4091838daf677b504d40.png)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)