Search code examples
javahibernatetransactionstry-catch-finally

Hibernate transaction: what is the point of this code?


In my project the following code is being used to manage hibernate transactions:

public void someMethod() {
    Session session = HibernateSessionFactory.getSession();
    Transaction tx = session.beginTransaction();
    try {
        session.save(something);
    } catch (Exception e) {
        tx.rollback();
        logger.error("error", e);
        throw new EJBException(e);
    } finally {
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            logger.error("error", e);
        } finally {
            session.close();
        }
    }
}

They told me this is done in order to make sure the connection has been properly closed at the end of the method. However I don't understand the point of doing the commit / rollback inside the finally block.

Is there a real reason that justifies this approach, or is it better to do something simpler, just like this?

public void simplerMethod() {
    Session session = HibernateSessionFactory.getSession();
    Transaction tx = session.beginTransaction();
    try {
        session.save(something);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        logger.error("error", e);
        throw new EJBException(e);
    } finally {
        session.close();
    }
}

Solution

  • It should be in try, for two reasons:

    You'll commit the session if some exception or error other than a HibernateException, and you almost certainly don't want to do that

    You'll call commit after calling rollback. I can't remember whether Hibernate allows you to do that (by silently ignoring the rollback) but at the very least it's ugly. Every session should either be committed or rolled back.