Spring TransactionTemplate导致双重提交

时间:2014-10-28 00:58:43

标签: spring spring-transactions

我有这种情况:

@Service
public class BeanA {

  @Transactional
  public void doSomething() {
    List<MyEntity> entities = repository.findAll();

    entities.stream.filter(MyEntity::methodUsingLazyLoading)
      .forEach(entity -> beanB.doSomethingMore(entity));
  }
}

@Service
public class BeanB {

  private final TransactionTemplate transactionTemplate;

  @Autowired
  public BeanB(PlatformTransactionManager transactionManager) {
    this.transactionTemplate = new TransactionTemplate(transactionManager);
  }

  public void doSomethingMore(MyEntity entity) {
    transactionTemplate.setPropagationBehavior(
        TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            entity.changeStatus();
        }
    });
  }
}

我在BeanA中执行doSomething方法。它看起来很简单,但问题是无论是在doSomethingMore方法中保存(和刷新)的实体(由于值的变化),Spring都会在完成doSomething方法的执行后再次保存它(另一次提交使用flush )。我在这里缺少什么?

0 个答案:

没有答案