Are Habernate programmatic transactions automatically rolled back with an unhandled exception?

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(); } 
+4
source share
1 answer

How about using declarative transaction demarcation ?

By default, all RuntimeExceptions cause rollbacks, but you can configure it to rollback in all exceptions.

AFAIK you should be aware of some errors, for example: you cannot comment everything with @Transactional , only classes or public beans methods.

0
source

Source: https://habr.com/ru/post/1299144/


All Articles