Spring #transactional is not rolling back for a RuntimeException - spring

My Class is defined as
#Transactional
#Service
public class InteractionHistoryServiceImpl implements InteractionHistoryService {
Within the class I have a single method that makes 4 separate calls to separate DB2 stored procedures as follows (pseudo):
#Override
public void createInteractionHistory(String userId, String userChannel,
CreateInteractionHistoryRequestPayload requestPayload) {
dao.createInteractionHistory(userId, userChannel, viewableBy,
interactCode, systemCreationDateTime, partyGrpId,
interactionHistoryController);
dao.createInteractionHistoryDetails(userId, interactonDescription, interactionHistoryController);
dao.createInteractionHistoryDetailsLink(userId, componentId, objectId, objectType, correspondanceType, direction, interactionHistoryController);
dao.createInteractionHistoryDetailsLink(userId, componentId, documentId, DOCUMENT, correspondenceType, direction, interactionHistoryController);
}
Now in the final call I force an exception in the database by passing a field width that's too big so it cannot call the proc at all. This is captured and converted into a system exception that extends RuntimeException.
I've debugged this code after the exception and it feeds into the spring framework and appears to be rolling things back.
When I check the underlying tables I can see that all the previous stored procs have succeeded and not rolled back but the final call did not succeed.
This is leaving me with inconsistent data and a headache as my understanding is that these should be handled all or nothing commit/rollback.
I've checked the stored procs and there are no commits going on in the database.
Any ideas here?

You need to consider your transaction boundary. Transaction boundary is typically where your BEGIN TRANSACTION and COMMIT / ROLLBACK statement is executed, and it's not entirely up to Spring, but could also be database implementation dependant.
Specifying #Transactional at the class level indicates every single public method of the class has a declarative transaction boundary (ie: a transaction will be started before the method executes, comitted when method finished / rolled back when exceptions occured)
In your case, it seems you did not enclose the 4 createInteractionHistory invocation in one single transaction -- and they are 4 separate transactions instead. Hence when the last one failed, the first 3 already succeed.
However even though you enclosed all those 4 invocation in a single transaction, it is not guaranteed that all your SQL will run in one transaction, since it depends on what code you have inside your stored proc and how DB2 draws the transaction boundary.
I suggest you spend some time on Spring transaction boundary and propagation topics -- and also DB2 transactions. Chapter 11 of the spring manual is a good reference.

Related

Nested transaction in SpringBatch tasklet not working

I'm using SpringBatch for my app. In one of the batch jobs, I need to process multiple data. Each data requires several database updates. And I need to make one transaction for one data. Meaning, if when processing one data an exception is thrown, database updates are rolled back for that data, then keep processing the next data.
I've put all database updates in one method in service layer. In my springbatch tasklet, I call that method for each data, like this;
for (RequestViewForBatch request : requestList) {
orderService.processEachRequest(request);
}
In the service class the method is like this;
Transactional(propagation = Propagation.NESTED, timeout = 100, rollbackFor = Exception.class)
public void processEachRequest(RequestViewForBatch request) {
//update database
}
When executing the task, it gives me this error message
org.springframework.transaction.NestedTransactionNotSupportedException: Transaction manager does not allow nested transactions by default - specify 'nestedTransactionAllowed' property with value 'true'
but i don't know how to solve this error.
Any suggestion would be appreciated. Thanks in advance.
The tasklet step will be executed in a transaction driven by Spring Batch. You need to remove the #Transactional on your processEachRequest method.
You would need a fault-tolerant chunk-oriented step configured with a skip policy. In this case, only faulty items will be skipped. Please refer to the Configuring Skip Logic section of the documentation. You can find an example here.

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.

Write call/transaction is dropped in TransactionalEventListener

I am using spring-boot(1.4.1) with hibernate(5.0.1.Final). I noticed that when I try to write to the db from within #TransactionalEventListener handler the call is simply ignored. A read call works just fine.
When I say ignore, I mean there is no write in the db and there are no logs. I even enabled log4jdbc and still no logs which mean no hibernate session was created. From this, I reckon, somewhere in spring-boot we identify that its a transaction event handler and ignore a write call.
Here is an example.
// This function is defined in a class marked with #Service
#TransactionalEventListener
open fun handleEnqueue(event: EnqueueEvent) {
// some code to obtain encodeJobId
this.uploadService.saveUploadEntity(uploadEntity, encodeJobId)
}
#Service
#Transactional
class UploadService {
//.....code
open fun saveUploadEntity(uploadEntity: UploadEntity, encodeJobId: String): UploadEntity {
// some code
return this.save(uploadEntity)
}
}
Now if I force a new Transaction by annotating
#Transactional(propagation = Propagation.REQUIRES_NEW)
saveUploadEntity
a new transaction with connection is made and everything works fine.
I dont like that there is complete silence in logs when this write is dropped (again reads succeed). Is there a known bug?
How to enable the handler to start a new transaction? If I do Propogation.Requires_new on my handleEnqueue event, it does not work.
Besides, enabling log4jdbc which successfully logs reads/writes I have following settings in spring.
Thanks
I ran into the same problem. This behavior is actually mentioned in the documentation of the TransactionSynchronization#afterCompletion(int) which is referred to by the TransactionPhase.AFTER_COMMIT (which is the default TransactionPhase attribute of the #TransactionalEventListener):
The transaction will have been committed or rolled back already, but the transactional resources might still be active and accessible. As a consequence, any data access code triggered at this point will still "participate" in the original transaction, allowing to perform some cleanup (with no commit following anymore!), unless it explicitly declares that it needs to run in a separate transaction. Hence: Use PROPAGATION_REQUIRES_NEW for any transactional operation that is called from here.
Unfortunately this seems to leave no other option than to enforce a new transaction via Propagation.REQUIRES_NEW. The problem is that the transactionalEventListeners are implemented as transaction synchronizations and hence bound to the transaction. When the transaction is closed and its resources cleaned up, so are the listeners. There might be a way to use a customized EntityManager which stores events and then publishes them after its close() was called.
Note that you can use TransactionPhase.BEFORE_COMMIT on your #TransactionalEventListener which will take place before the commit of the transaction. This will write your changes to the database but you won't know whether the transaction you're listening on was actually committed or is about to be rolled back.

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.

Spring transactions TransactionSynchronizationManager: isActualTransactionActive vs isSynchronizationActive

I am a little bit confused about transaction resource management in Spring. Namely, I am confused about the usage of TransactionSynchronizationManager.isActualTransactionActive and TransactionSynchronizationManager.isSynchronizationActive.
Up to now, probably incorrectly, I assumed that isSynchronizationActive was used (also within the Spring codebase) to figure out whether there is an active transaction, initiated by TransactionSynchronizationManager.initSynchronization(). As far as I am concerned, when we suspend a transaction, the actual isSynchronizationActive is still true! I presume, therefore, the correct way of establishing a running transaction is by using isActualTransactionActive, correct?
If this is the case, what is the actual point of isSynchronizationActive method? I understand it tells you whether you can add synchronizations or not, but I am a bit lost about what it tells us about the transaction...
You will notice the following fields of TransactionSynchronizationManager
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations");
private static final ThreadLocal<Boolean> actualTransactionActive =
new NamedThreadLocal<Boolean>("Actual transaction active");
and the methods
public static boolean isSynchronizationActive() {
return (synchronizations.get() != null);
}
public static boolean isActualTransactionActive() {
return (actualTransactionActive.get() != null);
}
The TransactionSynchronizationManager basically acts as a registry for TransactionSynchronization. The javadoc states
If transaction synchronization isn't active, there is either no
current transaction, or the transaction manager doesn't support
transaction synchronization.
So you first init and register TransactionSynchronization with initSynchronization() and registerSynchronization(TransactionSynchronization). When these are registered, the TransactionManager can start a Transaction and tell the TransactionSynchronizationManager if it's active or not with setActualTransactionActive(boolean).
In conclusion, isSynchronizationActive() tells us if TransactionSynchronization has been enabled, even if no TransactionSynchronization instances have been registered.
isActualTransactionActive() tells us if there is an actual Transaction object active.
The TransactionSynchronizationManager javadoc states
Central helper that manages resources and transaction synchronizations
per thread. To be used by resource management code but not by typical
application code.
so don't ignore it.

Resources