0

I clearly need some help about transaction roll back. I'm working on a Spring/JPA/Hibernate application.

For me, RuntimeException even if they are catched, are rolling back the transaction. I deduce this with some tests (that I can't put here unfortunatly as I don't have them anymore) and readings.

But I'm experiencing another behaviour with the following code :

public class Service implements IService {

  @Transactional
  public void test()
  {
    // ...
    try {
      throw new RuntimeException();
    } catch (RuntimeException re) {
    }
    foo.setBar(barValue);
    this.fooDao.save(foo);
  }
}

After executing this from the controller, the change on barparameter is present in my database which mean that the transaction has not been rollbacked.

Now the question

Does a catched runtimeException lead to a rollback or am I wrong ?

DessDess
  • 787
  • 1
  • 6
  • 20
  • Maybe I just don't understand what is going on here, but wouldn't you need to put the rollback code inside of the catch block? – Nora Powers Apr 22 '13 at 16:02
  • FWIW you're calling `fooDao.save(foo)` outside of the try-catch, so if that was causing the `RuntimeException`, then of course it will rollback since it wasn't caught. – xlm Oct 22 '18 at 00:37

1 Answers1

1

If you catch an unchecked exception e.g. RuntimeException, the transaction will not be rolled back.

By default, if your method exits because of an unchecked exception, then the transaction will be rolled back. Checked exceptions by default will not trigger rollback.

xlm
  • 6,854
  • 14
  • 53
  • 55
Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
  • 1
    Thanks, do you have an idea why in some case even if the runtimeexception was catched it leads to a roll back ? – DessDess Apr 22 '13 at 16:15