背景
我们知道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.