0

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!

beginnerCoder
  • 67
  • 1
  • 9
  • Please add the code for `methodB()` and `methodC()`. Additionally, please include all relevant transaction related annotations. Thanks! – João Dias Jan 12 '22 at 21:27
  • Try the solution on this [answer](https://stackoverflow.com/a/19354463/2933780) – galaxy Jan 15 '22 at 02:12

2 Answers2

0

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)

fladdimir
  • 1,230
  • 1
  • 5
  • 12
0

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.

See: https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back