c# - 我是否应该始终在 nhibernate 中使用事务(即使是简单的读写)?

标签 c# .net 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;
        }
    }  
}

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.

(顺便说一句,如果您正在认真地进行 NHibernate 工作,请考虑试用 NHProf)。

关于c# - 我是否应该始终在 nhibernate 中使用事务(即使是简单的读写)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304347/

相关文章:

c# - Linq to SQL 从不返回正确结果的查询中返回多个计数

c# - Windows 域登录可以包含超过 1 个 '\' 字符吗?

Javascript 设置表单属性

c# - 如何通过 NHibernate 在聚合根中处理具有持久计算属性的并发?

nhibernate - nhibernate 的 api 引用在哪里?

c# - Rhino mocks throws exception of "Callback arguments didn' t match the method arguments delegate"on the do 方法

c# - TreeView 的选定项目

c# - 将重复代码重构为方法

c# - 接口(interface)的默认实现是什么意思

.net - WCF .svc 可通过 HTTP 访问但访问 WSDL 导致 "Connection Was Reset"