我知道对于多部分写入,我应该在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();
}
}
}
答案 0 :(得分:21)
最好的建议是始终使用交易。 This link from the NHProf文档,最能解释原因。
当我们没有定义自己的时候 交易,它回归 隐式事务模式,其中每一个 对数据库的语句在其中运行 自己的交易,导致很大 性能成本(数据库时间到 建立和拆除交易),和 一致性降低。
即使我们只是阅读数据,我们也是 应该使用交易,因为 使用交易确保我们得到 来自数据库的一致结果。 NHibernate假定所有访问权限 数据库是在a下完成的 交易,强烈反对 没有使用会话的任何使用 事务。
(顺便说一句,如果你正在做认真的NHibernate工作,请考虑尝试NHProf)。