Java EE7 rollback a transaction

Viewed 160

I know that unchecked Exceptions (RuntimeExceptions) will usually cause a rollack of your transaction but what happens if you catch that exception in the same mothod? I want the rollback the whole transaction when errorOccurred is true. But I wonder if catching Exception will swallow the RuntimeException hence causing the transaction to NOT rollback? Does this code still rollback the transaction?

public static void main(String[] args) {
   try {
      // boring stuff...
      if(errorOccurred)
         throw new RuntimeException("RuntimeException is thrown.");
   } catch (Exception e) {
      System.out.println("RuntimeException cought. Does is still rollback transaction?");
   }
}
1 Answers

If your program catches the run time exception that means exception has not reached to JEE container, hence from JEE container perspective it is normal program execution, so it will not rollback transaction.

If you want to catch the runtime exception as well as rollback the transaction you need to programmatically rollback the transaction on those specific runtime exception. In session bean it provides sessioncontext object which has method setRollbackOnly , with this method you can inform the container to rollback transaction without throwing runtime exception. Message driven bean also provides messagedrivencontext object which can be used to rollack transaction[ check for MDB https://docs.oracle.com/javaee/6/tutorial/doc/bnbpo.html]

Related