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

我知道对于多部分写,我应该在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).

转载注明原文:c# – 我应该总是使用nhibernate中的事务(即使是简单的读写)? - 代码日志