NHibernate-是否真的需要ITransaction.Commit吗? [英] NHibernate - Is ITransaction.Commit really necessary?

查看:100
本文介绍了NHibernate-是否真的需要ITransaction.Commit吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两天前我才刚刚开始研究NHibernate,我正在寻找根据教程编写的CRUD方法. 我的插入方法是:

        using (ISession session = Contexto.OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(noticia);
            transaction.Commit();
            session.Close();
        }

"Contexto"的完整代码在这里: http://codepaste.net/mrnoo5

我的问题是:我真的需要使用 ITransaction transaction = session.BeginTransaction() transaction.Commit(); 吗?

我之所以这样问,是因为我测试了运行网络应用程序时没有这两行,并且我已经成功插入了新记录.

如果可能的话,有人也可以向我解释Itransaction的目的和Commit方法吗?

谢谢

解决方案

ITransaction transaction = session.BeginTransaction()并不是必需的,因为您通过测试发现了这一点.

但是想像一下,当您的会话引发异常时会发生什么?您将如何找回对数据库的更改?

以下是Nhib的报价...

典型的交易应使用以下习惯用法:

ISession sess = factory.OpenSession();
ITransaction tx; 
try 
{ 
    tx = sess.BeginTransaction(); //do some work ... 
    tx.Commit(); 
} 
catch (Exception e) 
{ 
    if (tx != null) 
    tx.Rollback(); 
    throw;
} 
finally 
{ 
    sess.Close(); 
}

如果ISession引发异常,则必须回滚事务 并且会话被丢弃. ISession的内部状态可能不是 发生异常后与数据库保持一致. NHibernate.ISessionFactory

I've just start studying NHibernate 2 days ago, and I'm looking for a CRUD method that I've written based on an tutorial. My insert method is:

        using (ISession session = Contexto.OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(noticia);
            transaction.Commit();
            session.Close();
        }

The complete code of "Contexto" is here: http://codepaste.net/mrnoo5

My question is: Do i really need to use ITransaction transaction = session.BeginTransaction() and transaction.Commit();?

I'm asking this because I've tested run the web app without those two lines, and I've successfully inserted new records.

If possible, can someone explain me too the purpose of Itransaction and the method Commit?

Thanks

解决方案

ITransaction transaction = session.BeginTransaction() is not necessary as you found out by testing.

But imagine this, what happens when your session throws an exception? how would you get back your changes to the database?

The following is quote from Nhib...

A typical transaction should use the following idiom:

ISession sess = factory.OpenSession();
ITransaction tx; 
try 
{ 
    tx = sess.BeginTransaction(); //do some work ... 
    tx.Commit(); 
} 
catch (Exception e) 
{ 
    if (tx != null) 
    tx.Rollback(); 
    throw;
} 
finally 
{ 
    sess.Close(); 
}

If the ISession throws an exception, the transaction must be rolled back and the session discarded. The internal state of the ISession might not be consistent with the database after the exception occurs. NHibernate.ISessionFactory

这篇关于NHibernate-是否真的需要ITransaction.Commit吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆