When working with software transactions in Hibernate, is it necessary to explicitly call a rollback when an exception occurs, or will the framework take care of calling the rollback if there is an unhandled exception? The code below looks like a safe approach (albeit an ugly code) to provide rollback, but I wonder if there is a more elegant way to code this, a thought?
ApplicationContext ac = new ClassPathXmlApplicationContext("hibernate-config.xml"); SessionFactory factory = (SessionFactory) ac.getBean("sessionFactory"); Session session = factory.getCurrentSession(); Transaction txn = null; try { txn = session.beginTransaction(); // <insert transaction work here> txn.commit(); } catch(Exception e) { try {txn.rollback(); } catch (Exception eAny) { } throw(e); } finally { session.close(); }
James source share