Spring Transaction Management to rollback the checked exception - spring

i am working on the Spring "#Transactional" Annotation to handle the transaction.
#Transactional(readOnly = false,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_UNCOMMITTED,rollbackFor=SQLException.class)
public void updateBatch(Report a)
throws SQLException, DataAccessException { insert1();insert2(); insert3(); }
But in case
insert1() - successfully inserts the data in table A.
insert2() - successfully inserts the data in table b
insert3() - throws the checked exception and does not insert data in table C
these inserts are ibatis inbuild functions to trigger the insert in DB
I got the following exception
"Caused by: org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:717)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)"
And the transaction would not get rolledback i.e. insert1(),insert2() does not get rollback
Please do let me know what i am missing

What are you doing in insert1 and insert2?
Are they using another transaction with PROPAGATION.REQUIRES_NEW attribute? If yes, they will not be rolled back. Else are you rolling back in insert1 or insert2?
I've experienced the same problem. Though it might be a bit different as the one you have. What I've had was a situation where you've got two services A and B.
A is calling a method of B in a try-catch block. B throws RuntimeException and the catch block of A wraps that exception into a catched exception.
What happened in my scenario:
- B is a separate class behind a transaction proxy
- B throws a runtime exception which sets transaction to rollback
- as I have Propagation.REQUIERED, it is the same transaction as the one for the method of A
- A wraps the exception and throws it as the exception is neither RuntimeException nor Error, the mention method will not proceed into transactionManager.rollback but to transactionManager.commit
- that would throw the UnexpectedRollback as the transaction was previously marked as rollback.
Your case might be different.

Related

How to set `noRollbackFor` on a `TransactionTemplate`?

Given that I have a TransactionTemplate set up like below (where I start a new transaction within an existing transaction), how do I prevent the parent (#Transactional) transaction from rolling back when code inside the child transaction throws a specific exception? Essentially, emulating the noRollbackFor parameter of #Transactional.
#Transactional
public void foo() {
bar();
}
private void bar() {
TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);
transactionTemplate.execute(__ -> {
// ...
});
}
This is not possible with a TransactionTemplate.
TransactionTemplate has no support for rollback rules.
See : https://github.com/spring-projects/spring-framework/issues/25086
This is by design: TransactionTemplate does not support custom
rollback rules. Technically TransactionTemplate isn't even aware of
TransactionAttribute since that variant is an extended definition only
supported by TransactionInterceptor (and therefore also living in the
latter's package). The template operates on plain
TransactionDefinition and uses fixed rollback behavior for all
exceptions thrown from its callbacks, effectively RuntimeExceptions
and Errors.
Alternatively, you may use the PlatformTransactionManager directly:
Inject it, call getTransaction on it, perform some resource
operations, then call commit in a finally block... and handle
potential runtime exceptions any way you need to, without calling
rollback. You may also selectively handle the outcome, as long as you
eventually call commit (or rollback, for that matter) to complete the
transaction.
An alternative solution to have more control over what gets rollbacked and what's should fail is using savepoints, see https://dzone.com/articles/transaction-savepoints-in-spring-jdbc
It is not 100% clear from your question, but note that if the exception is thrown inside the transactionTemplate.execute() method, only the inner transaction will be marked as rollback-only.
If you catch the exception e.g. in the foo method and don't let it bubble up to the outer transaction boundary, then the outer transaction still gets committed, while the inner was rolled back.
noRollbackFor is used to determine what happens to the inner transaction, i.e. whether it will be still committed, even though the lambda finishes with an exception.

How to avoid org.springframework.transaction.UnexpectedRollbackException?

When a method is annotated with #Transactional and there is an runtime exception, spring eats the exception and throws:
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
How do I avoid this "general" exception and propagate the original exception, but keeping the rollback?
Thanks.
org.springframework.transaction.UnexpectedRollbackException:
Transaction silently rolled back because it has been marked as
rollback-only
It mostly happens if you have an outer #Transactional method calls an inner #Transactional method. When the inner method throws an exception , but the outer method catches this exception and return normally, Spring is confused and don't know if it should rollback or commit the transaction since both methods contradict with each other. (Inner method says it wants to rollback but the outer method says it want to commit)
So , check if there are any outer #Transactional methods that catch the exception. If yes , re-throw that exception from the outer method such that the whole transaction will rollback.

Catch exception inside spring transaction and commit without rollback

Is it possible to catch exception inside spring transaction and commit without rollback?
You can specify exceptions to be ignored, in other words the commit will happen.
Example
#Transactional(noRollbackFor = SomeException.class)
Doc is here
Or you can just catch the exception, will have the same effect.

Spring JPA Service - Validation - Runtime Exception

I have a API , That looks like below
#Transaction
void method (){
try{
service1.insertOne();
service2.insertTwo();
}
catch(Exception ex) {
// log exception
}
}
In Service classes, I am checking for certain validation and I am throwing an exception which is a subclass of RuntimeException. When i throw this exception, javax.persistence.RollbackException: Transaction marked as rollbackOnly . While it is preventing the data in the first service from not being inserted , since the second service validation has failed, I am not quite quite sure if this is the right way to handle this scenario.
In case if the Exception is not a sub-class of Exception, even when the validation for service2 fails , data in service1 gets inserted, but i do see the custom exception being thrown. So i am not sure where i am going wrong. Any help is appreciated.
the Spring Framework’s transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-rolling-back
So, it must stay as a type of RuntimeException.
Probably you have Transactional annotation on top of service1.insertOne and/or service2.insertTwo() methods and that's why you get javax.persistence.RollbackException: Transaction marked as rollbackOnly.
You don't need those additional annotations (if they're exist) since there is an already active transaction.
Check this answer out.
If your insertOne, and insertTwo methods are marked as #Transactional, default propagation is Required. So you should see all that executed in one transaction. Link to docs
In second case it works as it should as well. If you throw custom transaction, then Spring does not take case of it. You can update that default behavior, by providing rollbackFor. In that case you will expect almost the same situation as in first case.
So it is more question to you - do you want your validation to mark transaction as rollbackOnly, or not. I would say yes.
Perhaps question is too abstract. Let's say you are putting invoice, and positions - then I would expect this transaction to be rolled back. However, if you add group, and users... Group can go, since problem is with user.
Just use the noRollbackForoption of the #Transactional to specify for which exception should not trigger a rollback:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#noRollbackFor--
#Transaction (noRollbackFor=YourRuntimeException.class)
void method (){
try{
service1.insertOne();
service2.insertTwo();
}
catch(Exception ex) {
// log exception
}
}
I am not quite quite sure if this is the right way to handle this scenario.
YES this way is fine, When you marked your method void method () as Transactional , you instructed whenever there is a runtime exception, please rollback . When a code block with in the #Transactional annotated method observes a runtimeexception during execution, the Spring framework will keep it is as flag ('rollbackOnly') under ThreadLocal variable. Please note that after completion of method() , spring will commit if it finds that the flag ('rollbackOnly') is false. Otherwise spring will instruct the transaction manager to rollback all of the inserts.
even when the validation for service2 fails , data in service1 gets inserted, but i do see the custom exception being thrown. So i am not sure where i am going wrong
As explained above.

How to rollback to savepoint nested transactions using Hibernate

I have a JavaEE application using Hibernate to connect to the database. In some part of my application I have calls to method which have a #Transactional annotation. In some of these cases, I want to rollback the whole transaction (the outer-service-method call, and the inner). And on some occasions I want to rollback only the inner service-method call (that is, rollback to savepoint defined at the start of the internal method).
The first part is already in place, but I have a problem with the second one. When I do the following, I get a "UnexpectedRollbackException" with the message "Transaction rolled back because it has been marked as rollback-only".
#Service
public class OuterService{
#AutoWired
private InnerServcie innerService;
#Transactional
public void outer(){
try{
innerService.inner();
}catch(RuntimeException e){
//if i dont throw this up, it will give me the "UnexpectedRollbackException"
System.out.println("I cought a RuntimeException");
}
}
}
#Service
public class InnerServcie{
#Transactional
public void inner(){
//here we insert some data into db using hibernate
//but something goes wrong and an exception is thrown
}
}
The feature you are looking for is called savepoints. They are not, strictly saying, nested transactions, but milestones in the consequent SQL instruction chain, to which you can rollback. Rolling back to savepoint means invalidating ALL instructions issued from the moment of creating the savepoint, so you can have multiple savepoints, but you can only rollback instructions between now and savepoint, not between 2 savepoints!
Spring supports savepoints, both when using JdbcTransactionObjectSupport manually, and using #Transactional annotation.
According to the document http://docs.spring.io/spring/docs/2.5.3/reference/transaction.html point 9.5.7.3 you should use Propagation.NESTED.
However, that options may not be available in your case. From Javadoc:
Note: Actual creation of a nested transaction will only work on
specific transaction managers. Out of the box, this only applies to
the JDBC DataSourceTransactionManager when working on a JDBC 3.0
driver. Some JTA providers might support nested transactions as well.
As last resort, you can issue SQL instructions starting/rollbacking to savepoint directly.
For PostgreSQL it would be:
SAVEPOINT foo;
ROLLBACK TO SAVEPOINT foo;
Source: http://www.postgresql.org/docs/8.2/static/sql-rollback-to.html
There is no support for nested transactions in Spring/Hibernate/Java EE. So, either the whole thing is rollbacked, or the inner transaction is actually a new, different transaction, that will be committed as soon as it succeeds, and even if the outer transaction rollbacks later.
If the latter is what you want, then simply annotate your inner method with
#Transactional(propagation = Propagation.REQUIRES_NEW)
Try setting the globalRollbackOnParticipationFailure attribute of your TransactionManager to false.
See http://docs.spring.io/spring/docs/3.1.4.RELEASE/javadoc-api/org/springframework/transaction/support/AbstractPlatformTransactionManager.html#setGlobalRollbackOnParticipationFailure(boolean) for more information.

Resources