我应该总是在nhibernate中使用事务(即使是简单的读写操作)吗?

vic*_*csz 14 .net c# nhibernate transactions

我知道对于多部分写入,我应该在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;
        }
    }  
}
Run Code Online (Sandbox Code Playgroud)

要么

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

简单的写作怎么样?

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

dri*_*iis 21

最好的建议是始终使用交易.来自NHProf文档的这个链接,最好地解释了原因.

当我们没有定义自己的事务时,它会回退到隐式事务模式,其中数据库的每个语句都在自己的事务中运行,从而导致大的性能成本(构建和拆除事务的数据库时间),以及降低的一致性.

即使我们只是读取数据,我们也应该使用事务,因为使用事务可以确保我们从数据库中获得一致的结果.NHibernate假定对数据库的所有访问都是在事务下完成的,并强烈反对在没有事务的情况下使用会话.

(顺便说一句,如果你正在做认真的NHibernate工作,请考虑尝试NHProf).