我正在使用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状态?
答案 0 :(得分: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(),因为当你的代码离开使用块时,它会自动执行,但是我再也记不住了。尝试一下,如果它不像我刚才描述的那样,你可以手动回滚捕获。
答案 1 :(得分: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 transactions了解更多详情