Everything I read about Hibernate states that you must roll back a transaction and close the session when an error occurs, and there's usually some variation of the following code (taken from Hibernate's docs) 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 odd to me for a couple of reasons. First, it just seems unreasonably complicated for a framework that's generally geared towards making things simple. More importantly, what happens if the code in the try
block throws something other than a RuntimeException
? It looks as if Hibernate must be able to gracefully close the session with an open transaction in that case, presumably by rolling it back, but if that's true, why bother calling rollback
at all?
Hibernate may make a lot of things simpler, but transaction management just isn't very simple so for every transaction you have to think very carefully what you want. Hibernate can't help you with that.
If the code in the try
block throws anything other than a RuntimeException
, your transaction obviously does not commit. But you do not explicitly rollback either. The sess.Close
call in your finally
block doesn't rollback the transaction either. What happens depends on whether this is a nested transaction:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With