where should we use commit(session), in try or finally?

If I want to use commit(session) after successful execution of database operation, where its better to put it in try or in finally block ? Here I used it in finally, should it be in try ?

public void delete( --- ) {
    Session session = init();
    try {
        ----
    } catch (HibernateException e) {
        rollback(session);
        logger.error("delete failed", e);
        throw e;
    } finally {
        commit(session);
        close(session);
    }
}
Jon Skeet
people
quotationmark

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.

The normal solution here is to keep a separate boolean variable which is set when you've successfully commit, and check that in finally, rolling back if necessary:

boolean committed = false;
try {
    // Do stuff
    commit(session);
    committed = true;
} catch (HibernateException e) {
    logger.error("delete failed", e);
    throw e;
} finally {
    if (!committed) {
        rollback(session);
    }
    // TODO: This won't execute if rollback fails.
    // Check whether that's a problem.
    close(session);
}

people

See more on this question at Stackoverflow