0

考虑 Hibernate 中的以下(简化)场景:

Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
try {
    //Do something with session
    if (...) {
        return something;
    }
    tx.commit();
}
finally {
    session.close();
}

在没有显式回滚的情况下返回是否是一种安全的做法,即在代码片段中调用没有显式回滚的 session.close() 语句是否会导致最终回滚?

4

1 回答 1

1

Not knowing how complex your real code may be, nevertheless, it is not best practice to not rollback in catch/finally. Here's how my current code looks like :

try{ .....

transaction = session.beginTransaction();  .....
// Finally commit the changes...
        transaction.commit();
}catch (Exception ex) {
        LOG.error(blah);
        transaction.rollback();
        throw new STDException("An error occured ",
                ex);
    } finally {
        session.close();
    }
于 2013-03-13T19:20:29.490 回答