Spring Hibernate eats exceptions - spring

With #Transaction and with trace level logging of Spring I see that Hibernate has an exception on a db constraint but it just rolls back the transaction. I tried using #Exception without success to try to catch it.
I see a suggestion online to use Spring AOP #AfterThrowing to catch such events.
This seems like a rather complex way to handle a commonplace event. It seems so much easier with try/catch and old fashioned commits/rollbacks. Is there no better way
in Spring Hibernate?
I'm processing XML messages from a queue. Depending on the type of the exception I get I might want to just catch it and put the bad incoming queue message into an db error table and continue the transaction. (If I just blindly rollback the message will get put back on the queue which might be good in some cases but not in others).
From what I've read there are ways of being made aware of some errors (for some reason not the constraint error) and logging them. Are there ways of interrupting the transaction after an exception and deciding if one wants to commit, continue or rollback?
If not, can one use old style commits and rollback with spring hibernate?

Configure SimpleMappingException resolver and log the exception there:
public class MyExceptionResolver extends SimpleMappingExceptionResolver {
private Logger logger = LoggerFactory.getLogger(MyExceptionResolver .class);
#Override
protected void logException(Exception ex, HttpServletRequest request) {
this.logger.warn(buildLogMessage(ex, request), ex);
}
<bean class="com.mypackage.MyExceptionResolver"/>
EDIT:
You can choose to do anything. The above class has nothing to do with rolling back. It's useful to intercept exceptions and do whatever you want with them.
By default, Spring rolls back for any RuntimeException.
If you want to configure rollback policy:
#Transactional(rollbackFor = { CustomException.class})
or
#Transactional(noRollBackFor= { CustomException.class})

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.

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.

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.

Resources