NHibernate:在提交事务之前调用Session.Flush()是否有效?

Not*_*sxl 8 .net c# nhibernate transactions flush

我需要在NHibernate的工作单元中执行两个操作:事务性(实体保存)和非事务性操作.

由于无事务操作无法回滚,如果我执行非事务操作(并最终提交事务)之前保存实体,我仍然会得到一个事务行为:

  • 仅当两个子操作成功执行时,才会提交操作;
  • 如果实体保存失败,则不执行非事务操作;
  • 如果非事务性失败,则实体保存将被回滚.

问题:使用如下代码,NHibernate将不会执行实际的sql插入,直到调用transaction.Commit()(在内部调用session.Flush()):

        using (var transaction = session.BeginTransaction())
        {
            session.Save(entity);
            NotTransactionalOperationBasedOn(entity);

            transaction.Commit(); // the actual sql insert will be executed here
        }
Run Code Online (Sandbox Code Playgroud)

使用这样的代码,如果Sql Insert失败则为时已晚:NotTransactionalOperation已执行.要在执行NotTransactionalOperation之前执行实际的SQL插入,我必须在session.Save()之前明确调用session.Flush():

        using (var transaction = session.BeginTransaction())
        {
            session.Save(entity);
            session.Flush(); // the actual sql insert will be executed here

            NotTransactionalOperationBasedOn(entity);

            transaction.Commit(); 
        }
Run Code Online (Sandbox Code Playgroud)

代码有效,但......在提交事务之前调用session.Flush()是最佳做法吗?如果没有,是否有更好的方法来实现相同的结果?

Fre*_*els 3

刷新意味着 NHibernate 将确保所有更改都保存到数据库中。也就是说,它将确保执行所有必要的 SQL 语句。当事务失败并因此回滚时,所有​​这些更改都将被恢复。因此,我认为这样做没有问题(但是您必须记住,您的实体可能不处于有效状态,因为事务已失败)。

但是......我实际上没有看到问题:当非事务性过程失败时,问题是什么?由于该过程是非事务性的,我想它对数据库保存的信息没有影响?或者,这段代码的作用是什么?

如果它是非事务性的,为什么不能在工作单元之外进行呢?

当保存失败时,我想您将确保不仅事务被回滚,而且异常也会被抛出到堆栈上,直到遇到错误处理程序,这可能意味着您的非事务处理程序代码也不会被执行:

using( var transaction = session.BeginTransaction() ) 
{
      repository.Save (entity); 

      transaction.Commit();   // error, exception is thrown.
}

NonTransactionalCode (entity); // this line will not be executed, since the exception will be thrown up the stack until a suitable catch block is encountered.
Run Code Online (Sandbox Code Playgroud)

  • 我知道这有点不寻常,但是 NonTransactionalCode(entity) 代表保存到远程硬件设备的实体,而 db 条目代表对该硬件的成功写入;所以我不能有一个远程保存不成功的数据库条目,反之亦然。:)(错误仍然由异常日志记录机制处理)我的怀疑来自于 transaction.Commit 在内部调用 Flush() 的事实,而我最终调用了 Flush() 两次。 (2认同)
  • 即使刷新成功,如果提交失败怎么办? (2认同)