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.