背景
我们知道update库表里的一条数据会产生行锁(以mysql innodb为例),提交事务后才会释放行锁,在行锁阶段别的事务无法去修改同一条记录。
在 Navicat 和命令行中,执行完这条update的 SQL 就立即提交事务。但是在Java程序里,用 @Transactional 修饰的方法只有执行完毕后才会提交事务。
除了update 语句,select for update 语句也是可以产生行锁的(也不一定是行锁,也可能表锁),可以用于临时锁定一行记录不被修改。
今天研究的课题就是研究下 select for update 的细节
代码直接上代码
- Rest 接口
@RestController
public class TestRest {
@Autowired
@Qualifier("testService1Impl")
private TestService testService1;
@Autowired
@Qualifier("testService2Impl")
private TestService testService2;
@Autowired
@Qualifier("testService3Impl")
private TestService testService3;
@Autowired
@Qualifier("testService4Impl")
private TestService testService4;
@GetMapping("/testSelectForUpdate1")
public Object testSelectForUpdate1(@RequestParam Integer id) {
return testService1.selectForUpdate(id);
}
@GetMapping("/update1")
public String update1(@RequestParam Integer id) {
String remark = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());
return "affected:" + testService1.update(id, remark);
}
@GetMapping("/testSelectForUpdate2")
public Object testSelectForUpdate2(@RequestParam Integer id) {
return testService2.selectForUpdate(id);
}
@GetMapping("/update2")
public String update2(@RequestParam Integer id) {
String remark = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());
return "affected:" + testService2.update(id, remark);
}
@GetMapping("/testSelectForUpdate3")
public Object testSelectForUpdate3(@RequestParam Integer id) {
return testService3.selectForUpdate(id);
}
@GetMapping("/update3")
public String update3(@RequestParam Integer id) {
String remark = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());
return "affected:" + testService3.update(id, remark);
}
@GetMapping("/testSelectForUpdate4")
public Object testSelectForUpdate4(@RequestParam Integer id) {
return testService4.selectForUpdate(id);
}
@GetMapping("/update4")
public String update4(@RequestParam Integer id) {
String remark = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());
return "affected:" + testService4.update(id, remark);
}
}
- Service实现类
其他 3 个Service实现类分别是:方法都去掉 @Transactional,去掉其中一个方法的 @Transactional
@Service
public class TestService1Impl implements TestService {
@Autowired
private TestMapper testMapper;
@Transactional
@Override
public MyTable selectForUpdate(int id) {
MyTable myTable = testMapper.selectForUpdate(id);
int totalSecs = 20;
for (int i = 0; i
关注
打赏
热门博文
- 防止电脑睡眠的Java程序
- 怎么在Windows10中找回Windows7的照片查看器(Windows 照片查看器)win10新的照片查看器太难用了
- IDEA的Terminal光标太粗了如何调细
- IDEA的Annotate或Annotate with Git Blame
- 如何搜素git某个分支是否存在?
- `git fetch` 和 `git remote update origin --prune` 的区别(以及跟`git pull` 的区别)
- 分支合并到b和b合并到a有区别吗
- Java 中如何比较两个BigDecimal 以及BigDecimal的坑
- 关于Springboot的@Profile的写法以及多个profile的写法排坑(“!profile1 && !profile2“ 的写法)
- 关于启动springboot如果指定多个profile时相同配置的覆盖规律