1

我正在使用 NHibernate 将一些数据插入表 A。如果表 A 事务失败,我想更新表 B 中的状态。如何检查它是否失败?

以下是我当前的代码:

// Add userId to Receiver
Receiver receiver = new Receiver();
receiver.User = User.GetById(Convert.ToInt32(listItem.Value));
receiver.Notification = Notification.GetById(notification.NotificationId);
receiver.Save();

我在哪里调用 NHibernate 事务?如果失败,我在哪里调用 NHibernate Rollback 并更新表 B 状态?

4

2 回答 2

6

查看有关异常处理的官方 NHibernate 文档:http: //nhibernate.info/doc/nh/en/index.html#manipulatingdata-exceptions

using ( ISession session = sessionFactory.OpenSession() )
{
    using ( ITransaction transaction = session.BeginTransaction() )
    {
        try
        {
            // Do your save/update here for Table A

            transaction.Commit();
        }
        catch( Exception e )
        {
            // Your save or update failed so this is where you
            // could capture that info and update your Table B

            transaction.Rollback();
        }
    }
}

据我记得,您实际上不必调用 tx.Rollback() 因为当您的代码离开 using 块时,它会自动执行此操作,但我记不清了。试一试,如果它的行为与我刚才描述的不同,您可以手动回滚捕获。

于 2012-08-17T19:45:40.663 回答
2
using (ISession session = factory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
    // do some work
    tx.Commit();
}

或手动

ISession session = factory.openSession();
try
{
   // do some work
   session.Flush();
   currentTransaction.Commit();
}
catch (Exception e)
{
   currentTransaction.Rollback();
   throw;
}
finally
{
   session.Close();
}

查看NHibernate 事务以获取更多详细信息

于 2012-08-17T20:18:57.763 回答