knowledge flow
knowledge flow

Reputation: 303

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

Upvotes: 3

Views: 3910

Answers (5)

Hassan Arafat
Hassan Arafat

Reputation: 56

You should commit transaction in the try block because this way you can rollback any error caused by the transaction commit itself. If you do transaction commit in the finally block and transaction commit throws error then your code will blow up.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503050

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

Upvotes: 7

kism3t
kism3t

Reputation: 1361

you need to put it in try block otherwise you would not recognize any error and you could not rollback

Upvotes: 0

René Winkler
René Winkler

Reputation: 7088

It should definitevly be placed in the try block. The finally block is usally only used to close any connection.

Upvotes: 0

Jens
Jens

Reputation: 69470

It should be in try. finally will also called after catch.

Upvotes: 0

Related Questions