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?