Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing rollback on transaction

I've a problem with the annotation @Transactional.

I've a method doing some stuff, and inside I throw and catch an IllegalArgumentException.

I think ( even if i've caught the exception ) that it sets the transaction as rollbackOnly ( some trigger on the throws of exception ) and it ends without succeeding to commit the transaction.

Here is the error:

org.springframework.transaction.TransactionSystemException : Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly

I could add on the @Transactional a no-rollback-for the exception I throw and catch, but i don't think it's a real solution.

Maybe there is a way to unset the rollbackOnly on the transaction but I don't think that it's the best practice too...

So, do you have any idea how should i do ?

Thanks,

like image 504
RoD Avatar asked Feb 24 '11 16:02

RoD


2 Answers

  1. Try / catch with IllegalArgumentException sounds like a code smell (Effective Java item 57: Use Exceptions only for exceptional conditions)

  2. Whether the transaction is set to rollbackOnly depends on the proxy mechanism used. If you use JDK proxies, the handler sits outside and has no way to register a caught exception inside the method call. If you use mode=aspectj, things will be different. Also, if you have nested transactional contexts, you will have to use @Transactional(noRollbackFor=IllegalArgumentException.class) on the inner method.

like image 148
Sean Patrick Floyd Avatar answered Nov 10 '22 06:11

Sean Patrick Floyd


If you can't commit the transaction then you probably have an exception in your code. By doing a try/catch, you conceal the full exception, and simply get a delicate generic explanation. You also get a rollback.

In order to understand your mistake, and to get the full description of your error, try to drop the try/catch thing and let the code explode. There you will see the real source of your problem.

like image 24
George Papatheodorou Avatar answered Nov 10 '22 08:11

George Papatheodorou