0

@Transactional(rollbackFor = someException.class)
public void methodA() throws someException {
    try {
        methodB();
    } catch (someException e) {
        throw e;
    }
}


public void methodB() throws someException {
    try {

        someManager.save(object); // This object should only save when the whole transaction is committed

        callToSomeOtherServer(); // This call fails and throws exception

    } catch () {
        throw new someException();
    }
}


According to my understanding, in methodB() we are saving an object with someManager and calling another function callToSomeOtherServer(). So this is part of a transaction in the upper method. If callToSomeOtherServer() fails and throws someException, the whole transaction should be rolled back and the saved object should not reflect in the DB.

But this is not working for me, the object is reflected in DB. Can someone help and make me understand why is it not working?

  • Please refer:: https://stackoverflow.com/questions/21188239/spring-transaction-rollback-on-exception-or-throwable – dassum Jul 30 '19 at 10:17
  • Instead of rollbackFor = someException.class, try rollbackFor = Exception.class – uneq95 Jul 30 '19 at 10:29
  • @dassum I have referred this. Still the issue prevails! – Hargur Bedi Jul 30 '19 at 10:30
  • Tried, still not working @uneq95. – Hargur Bedi Jul 30 '19 at 10:31
  • Please check methodB is throwing someException only. Also, it will be helpful if you can share the stack trace. – dassum Jul 30 '19 at 10:42
  • Which database are you using, please add your configuration. – M. Deinum Jul 30 '19 at 10:44
  • You don't need to catch and rethrow the exception, it only hinders readability here. Are you using Spring Boot or are you manually configuring transaction management ? if this is the case please paste your Configuration classes or XML config – Michael Técourt Jul 30 '19 at 10:48
  • 3
    Any chance you are [calling `methodA` from the same class](https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo) ? – Michael Técourt Jul 30 '19 at 10:50
  • Regardless the actual problem, and assuming the `callToSomeOtherServer` call doesn't need the object to be persisted (it won't until the transaction ends, anyway), I'd suggest rearranging the calls, so the persist line isn't reached when the external call throws the exception. – Luis Iñesta Jul 30 '19 at 10:50
  • Why do you catch an exception and again throw the same exception? – uneq95 Jul 30 '19 at 10:53
  • @Hargur: can you show the code from where you are calling this method. – Gagan Chouhan Aug 06 '19 at 12:03

1 Answers1

0

Try This!
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, readOnly = false, timeout = 100, rollbackFor = Exception.class)

MangduYogii
  • 935
  • 10
  • 24