What happens if you do not refuse a transaction in Hibernate?

Everything I read about Hibernate indicates that you should roll back the transaction and close the session when an error occurs, and, as a rule, some variants of the following code (taken from Hibernate docs) are given as an example:

Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); } 

This pattern seems strange to me for several reasons. Firstly, it just seems unreasonably complex for a structure that is generally oriented towards making things simple. More importantly, what happens if the code in the try block throws something other than a RuntimeException ? It seems that Hibernate should skillfully close the session with an open transaction in this case, presumably by returning it back, but if it is true, why call rollback at all?

+6
java orm hibernate transactions rollback
source share
2 answers

Hibernate can make it a lot easier, but transaction management is just not that simple, so for each transaction you have to think very carefully what you want. Sleep mode cannot help you with this.

If the code in the try block throws nothing but a RuntimeException , your transaction obviously does not commit. But you are clearly not rolling back. Calling sess.Close in your finally block also does not cancel the transaction. What happens depends on whether it is a nested transaction:

  • If this is not the case, then the transaction will expire and rollback.
  • If so, the parent transaction will see that the child transaction was not executed when it commits itself. This will roll back the entire transaction.
+4
source share

More importantly, what happens if the code in the try try block is something other than a RuntimeException?

If any other exception is possible in the code block in the try block other than a RuntimeException, it must be a checked exception that will be caught by the compiler itself, and you will eventually include some of the processing in your code.

In the example presented in this question, we catch only a RuntimeException, which I consider to be the correct way of coding. By doing this, we can cancel the transaction immediately, without waiting for the failure of the transaction and a possible rollback. As we continue to throw RuntimeException again, we also do not break the exception flow. This is a cleaner and more explicit way to deal with a transaction than allowing a transaction timeout to initiate a transaction rollback.

Of course, we should NOT catch the β€œException” in how the RuntimeException gets for obvious reasons.

0
source share

All Articles