2017-05-30 83 views
0

我有以下代码:当提交失败时,Nhibernate是否会回滚事务?

public void UpdateEntities() 
{ 
    Session.BeginTransaction(); 

    // add some entities there..... 

    Session.Transaction.Commit(); 
} 

如果Commt()失败,将回滚NHibernate的变化?

+1

请仔细阅读上面的链接,确保您正确地处理交易,如果可能,请使用“使用”声明。 –

回答

0

如果您查看AdoTransactionref)中的以下代码,您将看到NH在尝试提交时如何对错误做出反应。

if (session.FlushMode != FlushMode.Manual) 
{ 
    session.Flush(); 
} 

NotifyLocalSynchsBeforeTransactionCompletion(); 
session.BeforeTransactionCompletion(this); 

try 
{ 
    trans.Commit(); 
    log.Debug("DbTransaction Committed"); 

    committed = true; 
    AfterTransactionCompletion(true); 
    Dispose(); 
} 
catch (HibernateException e) 
{ 
    log.Error("Commit failed", e); 
    AfterTransactionCompletion(false); 
    commitFailed = true; 
    // Don't wrap HibernateExceptions 
    throw; 
} 
catch (Exception e) 
{ 
    log.Error("Commit failed", e); 
    AfterTransactionCompletion(false); 
    commitFailed = true; 
    throw new TransactionException("Commit failed with SQL exception", e); 
} 
finally 
{ 
    CloseIfRequired(); 
} 

虽然事务没有显式回滚,但它当然没有提交。因此,我认为你的问题的答案是肯定的,等待数据库更改将被回滚。

有意思的是,Flush()的电话没有包含在try中。因此,值得注意的是,这里捕获的异常可能会使Session处于不可预知的状态。因此,guidance处理异常。

+0

我明白了。因此,如果在提交失败时尝试在catch块中手动回滚,也存在问题。它在CheckNotZombied()检查时失败。 – Alexander