Reputation: 5168
My application is working on Spring MVC framwork and we have requirement to implement exception handling for process and DAO layer.
So, incase of any technical failure we Need to send Response Code 1 back to UI. So, the execution will happen in following manner.
Json Controller -> Delegate Layer -> Process Layer -> Servie Layer -> DAO Layer
I am using JPA in my application to persist the data in database and I am using Container managed transcation. But I have come across following queries while implementing Exception handling on DAO Layer :
Will JPA rollback the Transaction automatically even though I catch the Exception in DAO Layer ?
Should I catch RunTimeException on serviec layer, so In case of any failure on DAO Layer, I can set response code 1 on Service layer only ?
Do I Need to use @Transactional Annotation as I already have annotated my DAO class with @Repository Annotation ?
Upvotes: 0
Views: 105
Reputation: 1019
Will JPA rollback the Transaction automatically even though I catch the Exception in DAO Layer ?
No, it wont. The Exception should be progapated until spring catch it. To do that you have to rethrow the exception then spring will catch it and do its work.
Take a look to @Transactional docs.
Should I catch RunTimeException on service layer, so In case of any failure on DAO Layer, I can set response code 1 on Service layer only ?
Yes. Using @ControllerAdvice you can set a proper response to your UI. Eg: Rethrow a MovieServiceException then catch it with @ExceptionHandler and return a proper response.
Do I Need to use @Transactional Annotation as I already have annotated my DAO class with @Repository Annotation?
You should use @Transactional in your service layer because just setting @Repository wont work. If you are working with Spring Data JPA you may or not use @Transactional that's depends on your case.
UPDATE
I am throwing the exception from DAO layer but only different is I am not throwing original exception one but I do wrap the JPA exception with my application exception class and throwing it back to Service layer . So will rollback Operation work in that case also ?
Docs says: By default, a transaction will be rolling back on RuntimeException and Error but not on checked exceptions (business exceptions).
(I've seen people setting @Transactional(rollbackFor = Exception.class) so this should do work for the second case)
Could you please explain more Details why we dont Need @Transactional Annotation while working with Spring JPA Data ? And why do we Need it in other cases?
Simple, that's the default behavior. You can read more about it at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions
Upvotes: 1