0

I am having trouble with Spring Transactions. I need my catch block to persist some state on a forked/autonomous transaction then throw an exception to rollback whatever there was done on the primary transaction.

  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.READ_COMMITTED,
      rollbackFor = {Exception.class})
  public void createApplication() {
    try {
      saveState(0);
    } catch(Exception e) {
      saveState(1);

      throw e;
    }
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void saveState(Integet stateId) {
    ...
  }

The issue with this setup is that everything gets rollbacked (as mentioned in How to partially rollback data in spring boot, errors to be persited). Is there a way to fork transactions in Spring or this way is fundamentally incorrect?

I've also tried pairing Propagation.REQUIRED with Propagation.NESTED without avail.

downvoteit
  • 588
  • 2
  • 7
  • 12
  • This won't work, as it is an internal method call. – M. Deinum Jul 05 '21 at 11:33
  • Currently, `@Transactional` on `saveState` is ignored. To make your `saveState` transaction work, you need to use AspectJ or inject your service in itself. More info in answers to this question https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo – geobreze Jul 05 '21 at 11:33

1 Answers1

0

This is not working because you are having your second @Transactional method in the same class. Remember that @Transactional only works if the call goes through the proxy. Just move this saveState to another class and I am sure it is going to work because the rest of your code is perfectly correct.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70