Reputation: 5868
I was reading about the rollbackFor attribute when using JPA.
Right now my code is this
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void newUser(User user) {
try{
userRepository.saveAndFlush(user);
}catch(Exception e){
//log exception
}
return;
}
As far as I know, the rollbackFor will work when an exception is captured... is this the proper way to do it? or the try catch should not be there?
Thanks.
Upvotes: 3
Views: 1571
Reputation: 22442
Transactional Annotation rollbackFor: Defines zero (0) or more exception classes, which must be subclasses of Throwable, indicating which exception types must cause a transaction rollback.
Also, We should not suppress/eat the exception within the transactional method, rather we need to throw the Exception out from the method in order to roll back the database transaction:
Please find the proper implementation below:
@Transactional(readOnly = false,
propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void newUser(User user) throws Exception {
try{
userRepository.saveAndFlush(user);
} catch(Exception e){
throw new Exception("Unable to Save User Object ",e);
}
}
You can also refer the below link for handling exceptions for Transactional annotation:
Best practices for rolling back transactions in Spring 3/Hibernate
Upvotes: 2