一项JpaRepositories方法的交易 [英] One transaction for several JpaRepositories' methods

查看:90
本文介绍了一项JpaRepositories方法的交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些自动接线的接口扩展了JpaRepository.他们每个人都有针对不同实体的更新" hql方法.我从服务的方法中调用这些方法.

I have some autowired interfaces extends JpaRepository. Each of them has "update" hql method, for different entities. I'm calling these methods from service's method.

如果其中之一会失败,我如何使它们全部在一个事务中执行以回滚所有数据?

How i can make all of them executing in ONE transaction for rolling back all data, if one of them will fail?

service具有属性@service& @transactional,但无济于事.

service has attribuites @service & @transactional, but it doesnt help.

------------------------更新

------------------------ update

这里是一个例子. repository1.updateMethod()和repository2.updateMethod()可以正常工作,repository3.save会由于约束错误而引发异常.结果,我看到保存了repository1和repository2方法的结果.我需要它回滚.

Here an example. repository1.updateMethod() and repository2.updateMethod() works fine, repository3.save throws exception bacause of constraint error. In result, i see that results of repository1 and repository2 methods saved. I need it to roll back.

@ Service
@ Transactional(rollbackFor = {RuntimeException.class})
public SomeService {
  @ Autowired SomeRepository repository1;
  @ Autowired AnotherRepository repository2;
  @ Autowired ThirdRepository repository3;
  ...
  @ Transactional(rollbackFor = {RuntimeException.class})
  public void SomeMethod(SomeEntity obj, String someNewValue) {
    try {
      repository1.updateMethod();
      repository2.updateMethod();
      obj.setValue(someNewValue);
      repository3.save(obj);
    } catch (Exception ex) {
      throw new RuntimeException();
    }   
  }
}

推荐答案

我认为我找到了一种解决方案,但我仍然不明白为什么它不能在默认用法下使用.

I think i found one solution, but I still dont understand why it doesnt work with default usage.

首先,我在applidationData.xml中声明了JpaTransactionManager

First, I declared JpaTransactionManager at applidationData.xml

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

并用于服务:

@Autowired
JpaTransactionManager jtm;

在添加我的代码之前:

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("TxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus ts = jtm.getTransaction(def);

最后

jtm.commit(ts);

现在,如果某些方法产生异常,它将抛出最后一行,并且所有更新都将回滚.那就是我所需要的.但是,正如我说的那样,我仍然不明白为什么它在默认用法下不起作用.

Now, if some method produces exception, it throws at the last line and all updates is rolling back. That is what i needed. But, as i said, I still dont understand why it doesnt work with default usage.

这篇关于一项JpaRepositories方法的交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆