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

标签 java mysql spring hibernate transactions

我有两个服务,如下所示(简化代码):

@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 以编程方式使用事务解决了这个问题。

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

关于java - 使用 spring、hibernate 和 mysql 通过嵌套事务创建重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948597/

相关文章:

java char编码长度应该总是x乘2?

java - 应用程序关闭时清理 JSF session 范围 bean

javascript - 如何json编码一个字符串

PHP数据库从数据库中查询外键数据

java - @DataJpaTest 不读取 spring.jpa.* 属性,而 @SpringBootTest 读取

java - 使用 google commons 创建集合实例的通用 vs 静态声明

java - 使用 envers 列出每个实体的最新版本

MySQL 循环与 LOAD DATA LOCAL INFILE 一起使用

java - EnableConfigServer 不适用于 Spring Boot 中的 native 位置

java - 使用@PATCH 方法进行 Spring REST 部分更新