我有两个服务,如下所示(简化代码):
@Service
public class OuterService {
@Autowired
InnerService innerService;
@Transactional
public void doSomething() {
List<SomeEntity> list = entityRepo.findByWhatever(...);
for(SomeEntity listElement : list) {
innerService.processEntity(listElement);
}
}
}
@Service
public class InnerService {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void processEntity(Entity entity) {
// ...
StatusElement status = new StatusElement(...);
statusElementRepo.save(status);
}
}
现在可以通过退出 InnerService.processEntity()
来插入构造的 StatusElement
,并通过退出 OuterService.doSomething() 来再次插入
.
如果我将 OuterService.doSomething()
的 @Transactional
注释更改为 @Transactional(readOnly = true)
,它就会插入一次。
是MySql的问题(因为它可能不支持嵌套事务),我是否需要特殊的事务管理器,或者我的代码有问题? TIA!
最佳答案
我通过使用 PlatformTransactionManager
以编程方式使用事务解决了这个问题。
关于java - 使用 spring、hibernate 和 mysql 通过嵌套事务创建重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948597/