1

Below is structure of my method:

    @Override
    @Transactional
    public methodOuter(){
      //some processing
      methodInner1();
      methodInner2();
    }

    @Override
    @Transactional
    public methodInner1(){
    //save something to db
    }

    @Override
    @Transactional
    public methodInner2(){
    //some processing
    //throws exception
    }

Scenario is methodInner1() is processed successfully but methodInner2() throws exception. So i want to rollback commit done in methodInner1(). Currently commit in methodInner1() is not getting rolled back. I want methodOuter() to be in single transaction

Subash J
  • 2,028
  • 3
  • 13
  • 27
AkshayJ
  • 11
  • 3
  • There are different transaction modes that you can leverage here. I guess what you need is use existing else create new – Himanshu Bhardwaj Apr 26 '18 at 12:53
  • You can use `PROPAGATION_REQUIRED` on both `methodInner1()` and `methodInner2()` this will make all the methods to be executed in a single transaction. – Mouad EL Fakir Apr 26 '18 at 13:19

1 Answers1

2

If you know the type of the thrown exception (lets assume its a NPE) you could try something like

@Override
@Transactional(rollbackOn=NullPointerException.class)
public methodOuter(){
  //some processing
  methodInner1();
  methodInner2();
}

@Override
public methodInner1(){
  //save something to db
}

@Override
public methodInner2(){
  //some processing
  //throws exception
}

In that case you don't need to annotate the "Inner" functions. methodOuter will be rolled back if NullPointerException is thrown. If you want to Rollback for every possible Exception you should change the annotation to

@Transactional(rollbackOn=Exception.class)

By the way: RuntimeExceptions will cause a rollback whether they are annotated or not.

Christian Riese
  • 594
  • 1
  • 5
  • 18