【问题标题】:Duplicate object creation with nested transactions using spring,hibernate and mysql使用 spring、hibernate 和 mysql 使用嵌套事务创建重复对象
【发布时间】:2015-11-04 01:57:33
【问题描述】:

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

@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 的问题(因为它可能不支持嵌套事务),我需要一个特殊的事务管理器,还是我的代码有问题?蒂亚!

【问题讨论】:

  • Hibernate 本身不支持嵌套事务,并且 REQUIRES_NEW 不是嵌套事务,只是一个单独的事务。该代码未显示 Entity 和 StatusElement 实体是否或如何交互。如果他们这样做(例如将状态添加到实体中的状态列表中),并且这两个服务实际上使用不同的会话(由于事务处理),则您可能会将 StatusElement 对象从 processEntity Session 泄漏到 Session的doSomething,导致自动持久存在以及您明确的“保存()”。

标签: java mysql spring hibernate transactions


【解决方案1】:

我通过使用PlatformTransactionManager 的程序化事务解决了这个问题。

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

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 2018-07-29
    • 2021-11-17
    • 2015-07-21
    • 1970-01-01
    • 2011-08-04
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多