我在使用Spring和Hibernate的一个应用程序中工作,并且处理事务时遇到了问题。我得到了一个服务类,它从数据库中加载一些实体,修改它们的一些值,然后(当一切都有效时)将这些更改提交给数据库。如果新值无效(我只能在设置它们后才能检查),我不想坚持更改。为了防止Spring / Hibernate保存更改,我在该方法中抛出异常。但是,这会导致以下错误:
无法提交JPA事务:标记为rollbackOnly的事务 $ c这是服务: pre $ @Service class MyService { @Transactional(rollbackFor = MyCustomException.class)$ b $ public void doSth()throws MyCustomException { //从数据库加载实体 //修改它们的一些值 //检查它们是否有效 if(invalid){//如果它们不是有效的,抛出异常 throw new MyCustomException(); } } }
是我如何调用它:
class ServiceUser { @Autowired private MyService myService; public void method(){ try { myService.doSth(); } catch(MyCustomException e){ // ... } } }我希望发生的事情:没有对数据库进行更改,也没有任何用户可见的异常。
发生了什么:数据库没有更改,但应用程序崩溃:
org.springframework.transaction.TransactionSystemException:无法提交JPA交易; 嵌套异常是javax.persistence.RollbackException:标记为rollbackOnly的事务正确设置事务到rollbackOnly,但为什么回滚与异常崩溃?
解决方案我的猜测是 ServiceUser。 method()本身是事务性的。它不应该。这是为什么的原因。
以下是调用 ServiceUser.method()方法时会发生的情况: $ b
现在如果 ServiceUser。 method()不是事务性的,这是发生了什么:
I'm using Spring and Hibernate in one of the applications that I'm working on and I've got a problem with handling of transactions.
I've got a service class that loads some entities from the database, modifies some of their values and then (when everything is valid) commits these changes to the database. If the new values are invalid (which I can only check after setting them) I do not want to persist the changes. To prevent Spring/Hibernate from saving the changes I throw an exception in the method. This however results in the following error:
Could not commit JPA transaction: Transaction marked as rollbackOnlyAnd this is the service:
@Service class MyService { @Transactional(rollbackFor = MyCustomException.class) public void doSth() throws MyCustomException { //load entities from database //modify some of their values //check if they are valid if(invalid) { //if they arent valid, throw an exception throw new MyCustomException(); } } }And this is how I invoke it:
class ServiceUser { @Autowired private MyService myService; public void method() { try { myService.doSth(); } catch (MyCustomException e) { // ... } } }What I'd expect to happen: No changes to the database and no exception visible to the user.
What happens: No changes to the database but the app crashes with:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnlyIt's correctly setting the transaction to rollbackOnly but why is the rollback crashing with an exception?
解决方案My guess is that ServiceUser.method() is itself transactional. It shouldn't be. Here's the reason why.
Here's what happens when a call is made to your ServiceUser.method() method:
Now if ServiceUser.method() is not transactional, here's what happens:
更多推荐
无法提交JPA事务:标记为rollbackOnly的事务
发布评论