【问题标题】:Hibernate transaction: what is the point of this code?Hibernate 事务:这段代码的意义何在?
【发布时间】:2017-03-17 10:11:38
【问题描述】:

在我的项目中,以下代码用于管理休眠事务:

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

【问题讨论】:

    标签: java hibernate transactions try-catch-finally


    【解决方案1】:

    应该试试,有两个原因:

    如果出现 HibernateException 以外的异常或错误,您将提交会话,并且您几乎肯定不想这样做

    在调用回滚后你会调用 commit。我不记得 Hibernate 是否允许你这样做(通过默默地忽略回滚),但至少它是丑陋的。每个会话都应该提交或回滚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 2020-05-07
      • 2016-03-28
      相关资源
      最近更新 更多