javahibernateexceptiontry-catch

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);
    }
}

Solution

  • It should be in try, for two reasons:

    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);
    }