0
在我的项目下面的代码被用于管理Hibernate事务:Hibernate事务:这段代码的重点是什么?
public void someMethod() {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
try {
session.save(something);
} catch (Exception e) {
tx.rollback();
logger.error("error", e);
throw new EJBException(e);
} finally {
try {
tx.commit();
} catch (Exception e) {
tx.rollback();
logger.error("error", e);
} finally {
session.close();
}
}
}
他们告诉我这是为了确保连接已在方法的末尾正确关闭的完成。不过,我不明白在finally
块中执行提交/回滚的重要性。
是否有真正的理由证明这种方法的正确性,还是更好地做一些简单的事情,就像这样?
public void simplerMethod() {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
try {
session.save(something);
tx.commit();
} catch (Exception e) {
tx.rollback();
logger.error("error", e);
throw new EJBException(e);
} finally {
session.close();
}
}