Repository.SaveOrUpdate(),异常时执行回滚的确定性?
为了保存(虚拟)银行帐户交易列表,我希望业务实体能够反映保存到数据库的状态,即使出现异常也是如此。
我可以假设这里的异常也意味着事务被回滚吗?或者我可以明确回滚 catch 以确定吗?如果是这样,如果该行抛出异常怎么办?
在存储库中< T>:
public void SaveOrUpdate(IList<T> entityList)
{
using (ISession session = FluentNHibernateManager.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
foreach (T entity in entityList)
session.SaveOrUpdate(entity);
transaction.Commit();
}
catch (Exception e)
{
MyTrace.Exception(e.ToString());
// add this line? transaction.Rollback();
throw;
}
}
}
}
在某些类中:
cashTransactions.Add(t);
try {
GenericRepository<CashTransaction> repo = new GenericRepository<CashTransaction>();
repo.SaveOrUpdate(cashTransactions);
} catch (Exception ex) {
cashTransactions.Remove(t);
}
For saving a list of (virtual) bank account transactions, I want the business entity to reflect the state saved to database, also in case of an exception.
Can I assume that an exception here also means the transaction is rolled back? Or can I explicitly rollback in the catch to be sure? If so, what if that line throws an exception?
In Repository< T >:
public void SaveOrUpdate(IList<T> entityList)
{
using (ISession session = FluentNHibernateManager.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
foreach (T entity in entityList)
session.SaveOrUpdate(entity);
transaction.Commit();
}
catch (Exception e)
{
MyTrace.Exception(e.ToString());
// add this line? transaction.Rollback();
throw;
}
}
}
}
In Some Class:
cashTransactions.Add(t);
try {
GenericRepository<CashTransaction> repo = new GenericRepository<CashTransaction>();
repo.SaveOrUpdate(cashTransactions);
} catch (Exception ex) {
cashTransactions.Remove(t);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能假设事务已回滚,但也不必假设:
ITransaction
具有bool WasCommited
属性。您可以检查以确定事务是否已提交,并在必要时显式调用
Rollback()
。You can't assume that the transaction was rolled back, but you don't have to assume:
ITransaction
has abool WasCommitted
property.You can check that to determine whether the transaction was committed, and call
Rollback()
explicitly, where warranted.您必须包含 rollback() 调用才能正确回滚事务。
You've gotta include the rollback() call to rollback the transaction properly.
处置未提交的事务总是会回滚它。
这在所有 ado.net 事务实现中都是如此,当然在运行时 NHibernate 将使用您选择的 ado.net 提供程序。
To dispose a not-commited transaction will always rollback it.
This is true in all ado.net transactions implementation, and of course at runtime NHibernate will use your chosen ado.net provider.