【问题标题】:Exception in commit tran in hibernate休眠中提交 tran 中的异常
【发布时间】:2015-05-14 01:29:43
【问题描述】:

我在使用休眠时遇到问题。

for Loop
  begin tran
  select record
  insert record
  commit tran
  if exception, rollback tran
end

在第一次出现时,我插入了一条外键值无效的记录,然后在提交事务时抛出异常。 在第二次出现时,我选择记录或插入正确的记录,它会抛出异常,该异常属于第二次出现。

由于 for 循环中的每次出现都没有依赖关系,因此,我想提交那些正确的记录,而只回滚那些无效的记录。我该怎么做?

【问题讨论】:

    标签: hibernate exception transactions commit


    【解决方案1】:

    试试下面的代码:

    for (...) {
        Session s = sessionFactory.openSession();
        try {
            s.beginTransaction();
            // do work...
            s.getTransaction().commit();
        } finally {
            if ( ! s.getTransaction().isActive())
                try { s.getTransaction().rollback(); }
                catch (Exception ignored) {
                    log.warn("Ignored rollback error", ignored); 
                }
            s.close();
        }
    }
    

    Session's javadoc 说:

    如果Session抛出异常,事务必须滚动 返回并丢弃会话。 Session的内部状态 异常发生后可能与数据库不一致。

    创建会话很便宜,只要确保正确配置了连接池。如果您的工作单元非常小,则可能值得测试该场景,只有在异常之后您才会打开新会话,否则只需 clear() 它。

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 2021-12-08
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      相关资源
      最近更新 更多