If we catch the exception in method annotated with the @Transactional annotation, will it roll back if any exception occurs?
@Transactional(read
for example
class A{
@Transactional
public Result doStuff(){
Result res = null;
try {
// do stuff
} catch (Exception e) {
}
return res ;
}
}
If there is an exception in the method doStuff the transaction isn't rolled back.
To rollback the exception programmatically, we can do something like below.
declarative approach
@Transactional(rollbackFor={MyException1.class, MyException2.class, ....})
public Result doStuff(){
...
}
programmatic rollback
you need to call it from TransactionAspectSupport.
public Result doStuff(){
try {
// business logic...
} catch (Exception ex) {
// trigger rollback programmatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
You are strongly encouraged to use the `declarative approach` to `rollback` if at all possible.
`Programmatic rollback` is available should only be used if you absolutely need it.