I have this kind of code:
@Service
public class AService {
public void methodA() {
try {
methodB();
} catch (Exception e) {
methodC(e);
}
}
}
methodB is reading from DB. methodC is writing the Exception if occurred to the DB. for some reason, when method B throws an error, the writing in methodC is not working and I get - UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only.
would appreciate any advice on this, thanks!
CodePudding user response:
In case of an exception during DB access, Hibernate will generally mark the complete transaction as rollbackOnly, even if one would explicitly try to avoid this behavior via the @Transactional(noRollbackFor=Exception.class) annotation attribute.
So in these cases, there needs to be a different solution, such as having separate transactions for the two method calls.
(Similar problem: handle sql exception for large data insert)
CodePudding user response:
I assume you have a transaction managed by Spring (@Transactional) somewhere inside methodB. In Spring, a transaction is marked for rollback when a RuntimeException is thrown within this transaction.
From the Spring docs:
In its default configuration, the Spring Framework’s transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
