考虑Hibernate中的以下(简化)场景:
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
try {
//Do something with session
if (...) {
return something;
}
tx.commit();
}
finally {
session.close();
}
在没有显式回滚的情况下返回是安全的做法,即在代码片段中没有调用显式回滚的session.close()语句会导致最终回滚吗?
答案 0 :(得分:1)
不知道您的真实代码有多复杂,但是,最好不要在catch / finally中回滚。以下是我当前代码的样子:
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();
}