使用 spring、hibernate 和 mysql 使用嵌套事务创建重复对象

Duplicate object creation with nested transactions using spring,hibernate and mysql

我有两个服务,像这样(简化代码):

@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);
    }

}

构造的 StatusElement 现在通过退出 InnerService.processEntity() 插入,通过退出 OuterService.doSomething() 再次插入

如果我将 OuterService.doSomething()@Transactional 注释更改为 @Transactional(readOnly = true),它只会插入一次。

是MySql的问题(因为它可能不支持嵌套事务),我需要一个特殊的事务管理器,还是我的代码有问题? TIA!

我通过使用 PlatformTransactionManager.

以编程方式使用事务来解决它

参见:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-programmatic-ptm