views:

36

answers:

1

When working with programmatic transactions in Hibernate, is it necessary to explicitly call rollback if an exception occurs, or will the framework take care of calling rollback if there is an unhandled exception? The code below seems like the safe approach (albeit ugly code) to ensure rollback, but i'm wondering if there is a more elegant way of coding this, thoughts?

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(); }
+1  A: 

How about using Declarative Transaction Demarcation?

By default all RuntimeExceptions cause rollback, but you can tune it to rollback on all exceptions.

AFAIK you have to be aware of some gotchas, for example: you cannot annotate everything with @Transactional, only classes or public methods of beans.

pihentagy