加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我应该总是使用nhibernate中的事务(即使是简单的读写)?

发布时间:2020-12-15 18:09:40 所属栏目:百科 来源:网络整理
导读:我知道对于多部分写,我应该在nhibernate中使用事务.然而,对于简单的读取和写入(1部分??)…我已经看到,始终使用事务是个好习惯.这是否需要? 我应该如何做一个简单的阅读?或者我可以把转录部分放在一起吗? public PrinterJob RetrievePrinterJobById(Guid i
我知道对于多部分写,我应该在nhibernate中使用事务.然而,对于简单的读取和写入(1部分??)…我已经看到,始终使用事务是个好习惯.这是否需要?

我应该如何做一个简单的阅读?或者我可以把转录部分放在一起吗?

public PrinterJob RetrievePrinterJobById(Guid id)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            var printerJob2 = (PrinterJob) session.Get(typeof (PrinterJob),id);
            transaction.Commit();

            return printerJob2;
        }
    }  
}

要么

public PrinterJob RetrievePrinterJobById(Guid id)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        return (PrinterJob) session.Get(typeof (PrinterJob),id);              
    }
}

对于简单的写作呢?

public void AddPrintJob(PrinterJob printerJob)
{
    using (ISession session = sessionFactory.OpenSession())
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(printerJob);
            transaction.Commit();
        }
    }
}

解决方法

最佳建议是始终使用交易. This link from the NHProf文档,最好的解释为什么.

When we don’t define our own
transactions,it falls back into
implicit transaction mode,where every
statement to the database runs in its
own transaction,resulting in a large
performance cost (database time to
build and tear down transactions),and
reduced consistency.

Even if we are only reading data,we
should use a transaction,because
using transactions ensures that we get
consistent results from the database.
NHibernate assumes that all access to
the database is done under a
transaction,and strongly discourages
any use of the session without a
transaction.

(BTW,如果您正在严格的NHibernate工作,请考虑尝试NHProf).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读