【发布时间】:2022-01-12 22:38:17
【问题描述】:
如何防止 Spring 事务中的并发?
情况是两个请求并行的方法如下:
@Transactional
public save() {
Optional<Example> result = repository.findById(1);
if(!result.isPresent()) {
Example exemple = new Exemple();
exemple.setParam1(1);
exemple.setParam2(1);
exemple.setParam3(1);
exemple.setParam4(1);
exemple.setParam5(1);
exemple.setParam6(1);
exemple.setParam7(1);
exemple.setParam8(1);
repository.save(exemple);
}
}
因此,例如,第二个请求在第一个请求结束并提交之前通过“ifPresent”验证。导致意外行为并保存对象两次。
我需要使用@EnableTransactionManagement 吗?我需要在@Transactional 中使用一些值吗?
【问题讨论】:
标签: java spring spring-data-jpa spring-transactions