文章目录
一、(1)【新版】乐观锁
在面试过程中,我们经常会被问到乐观锁、悲观锁,这个其实很简单!
乐观锁:顾名思义,他非常乐观!总是认为不会出现问题,无论干什么都不去上锁!
如果出现问题,再次更新值测试
!悲观锁:顾名思义,他非常悲观!总是认为一定会出现问题,无论干什么都会上锁!再去操作!
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
测试一下MP(Mybatis—Plus)的乐观锁插件
1、给数据库中增加version字段!
2、我们实体类添加对应的字段!
@Version //乐观锁Version注解
private Integer version;
3、注册组件
@EnableTransactionManagement
@MapperScan("com.jin.mapper") //主程序入口中的这行代码可移过来!
@Configuration //配置类
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//注册乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
4、测试运行
//测试乐观锁是否成功!
@Test
public void testOptimisticLocker(){
//1、查询用户信息
User user = userMapper.selectById(1L);
//2、修改用户信息
user.setName("kuxiaoya111");
user.setEmail("kxy00521@163.com");
//模拟另外一个线程执行了插队操作
User user2 =userMapper.selectById(1L);
user2.setName("kuxiaoya222");
user2.setEmail("xxyyy@qq.com");
userMapper.updateById(user2);
//3、执行更新操作
userMapper.updateById(user);//如果没有乐观锁,就会覆盖插队线程的值!
}
🕳注意🕳:
以上文章展示的均是导入的3.4.0及其以上
的依赖版本,依赖如下:
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
导入的依赖版本过低,则报错!
如果你想使用旧版本的话,请接着往下看
一、(2)【旧版】乐观锁
导入低版本依赖
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
注册组件有所改变
@EnableTransactionManagement
@MapperScan("com.jin.mapper")
@Configuration //配置类
public class MyBatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
其余操作不变
二、查询操作
1、查询某个信息
//测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
2、查询多个信息
//查询多个信息
@Test
public void testSelectBatchIds(){
List<User> user= userMapper.selectBatchIds(Arrays.asList(1,2,3));
user.forEach(System.out::println);
}
3、条件查询map
//条件查询map
@Test
public void testMap(){
HashMap<String, Object> map = new HashMap<>();
//自定义要查询
map.put("name","酷小亚");
map.put("age","3");
List<User> userList = userMapper.selectByMap(map);
userList.forEach(System.out::println);
}
若想再深入了解Map传值
的话,
可看下这篇文章:https://blog.csdn.net/weixin_45737330/article/details/126081645