我应该总是在 nhibernate 中使用事务(即使是简单的读写)? [英] Should I always use transactions in nhibernate (even for simple reads and writes)?

查看:19
本文介绍了我应该总是在 nhibernate 中使用事务(即使是简单的读写)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对于多部分写入,我应该在 nhibernate 中使用事务.但是,对于简单的读写(1 部分)呢……我读到始终使用事务是一种很好的做法.这是必需的吗?

I know that for multi part writes, I should be using transactions in nhibernate. However what about for simple read and writes (1 part) ... I've read that it's good practice to always use transactions. Is this required?

我应该做以下简单的阅读吗??或者我可以把交易部分放在一起吗?

Should I do the following for a simple read ?? or can I just drop the transcaction part all togather ?

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();
        }
    }
}

推荐答案

最好的建议是始终使用事务.NHProf 文档中的此链接 最好地解释了原因.

Best recommendation would be to always use a transaction. This link from the NHProf documentation, best explains why.

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

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.

即使我们只是读取数据,我们应该使用事务,因为使用交易确保我们得到来自数据库的一致结果.NHibernate 假设所有访问数据库是在一个交易,并强烈反对没有使用会话的任何使用交易.

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).

(BTW, if you are doing serious NHibernate work, consider trying out NHProf).

这篇关于我应该总是在 nhibernate 中使用事务(即使是简单的读写)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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