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?
java orm hibernate transactions rollback
John williams
source share