Search code examples
springjpatry-catchspring-data-jpatransactional

Spring Data JPA + Hibernate : catch block inside a Transactional method is never reached


In our Spring Data JPA + Hibernate application, there are various methods having multiple JPA operations inside the same transaction - below is the code/configuration on one of the spring service methods.

@Transactional(rollbackFor=MyAppException.class)
public void updateCustomerprofile(String customerKey) throws MyAppException{
    try{
    CustomerId customerIdObj = customerIdRepository.findOne(customerKey);
    customerIdObj.setCreatedUser("<loggedin-user>");
     // more logic here
    customerIdObj = customerIdRepository.save(customerIdObj);
    }catch(DataAccessException dae){
        //this catch block is never reached even if there is an exception while saving because of JPA flusheing at the end of transaction
        throw new MyAppException(dae);
    }

}

It's been observed that the execution will never reach the catch block even if there is an exception thrown while saving the record - and it is because JPA flushes at the end of the transaction.

Where exactly should this catch block be placed?

Should we be catching DataAcccessException on the web layer (bean)?

If so, are we not taking the datalayer dependencies on to web layer?

If I have to wrap DataAccessException into my application specific exception, how do I do it?

Please suggest.


Solution

  • The problem here is that the exception is not thrown within your code, but when the container commits the transaction (see also this answer). To avoid using bean-managed transactions, you can:

    • Synchronize the persistence context via EntityManager.flush(),
    • Use an EJB interceptor with the @AroundInvoke annotation which begins, commits and rollbacks the transaction (similar approach to BMT), or
    • Wrap the code which is supposed to throw the exception in a method with @TransactionAttribute(REQUIRES_NEW).

    See also this thread, where some details about the REQUIRES_NEW approach are further explained.