简体   繁体   English

nhibernate 中的事务如何工作?

[英]How do transactions work in nhibernate?

I just started learning nHibernate and I'm confused by transactions.我刚开始学习 nHibernate,我对交易感到困惑。 I know that nhibernate tracks all changes to persistent objects in a session and those changes get sent to database on commit, but what is the purpose of the transactions?我知道 nhibernate 跟踪 session 中持久对象的所有更改,这些更改在提交时发送到数据库,但事务的目的是什么?

If I wrap code in a 'using transaction' block and call commit does it just commit the object changes that occurred within the transaction or does it commit all changes that occurred within the session since last commit of flush?如果我将代码包装在“使用事务”块中并调用提交,它只是提交事务中发生的 object 更改,还是提交自上次提交刷新以来 session 中发生的所有更改?

The purpose of transactions is to make sure that you dont commit a session with dirty data or error on it.事务的目的是确保您不会提交带有脏数据或错误的 session。 Consider the very simple case of a transaction of placing an order for a book.考虑下订单交易的非常简单的案例。

You will probably do the following actions: a) Check if the book exists at this moment.您可能会执行以下操作: a) 检查此时该书是否存在。 b) Read the customer details and see if he has anything in the shopping cart. b) 阅读客户的详细信息,看看他的购物车中是否有任何东西。 c) Update the book count d) Make an entry for the order c) 更新书数 d) 输入订单

Now consider the case where in you run into an error while the order is being entered obs you want your other changes to be rolled back and that is when you roll back the transaction.现在考虑在输入订单时遇到错误的情况,因为您希望回滚其他更改,即在您回滚事务时。

How do you do it?你怎么做呢? Well there are many ways.那么有很多方法。 One of the ways for web apps is to monitor the HTTP Error object as follows: web 应用程序的一种方法是监视 HTTP 错误 object 如下:

if(HttpContext.Current != null && HttpContext.Current.Error != null)
transaction.Rollback();

Ideally you should not break your unit of work pattern by using explicit transaction blocks.理想情况下,您不应该通过使用显式事务块来破坏您的工作单元模式。 Try to avoid doing this as much as possible尽量避免这样做

If you don't use transactions then anytime NHibernate sends a batch, that alone will be a transaction.如果您不使用事务,那么任何时候 NHibernate 都会发送一个批次,仅此一项就是一个事务。 I'm not sure if the session.Flush() uses a batch or not.我不确定 session.Flush() 是否使用批处理。 Let's suppose it does.让我们假设它确实如此。 Your first call to session.Flush() would result in a transaction.您第一次调用 session.Flush() 将导致事务。 Suppose your second call to flush results in a an error.假设您对刷新的第二次调用导致错误。 The changes from the first flush would remain in the DB.第一次刷新的更改将保留在数据库中。

If on the other hand you're using an explicit transaction, you can call flush a million times but if you roll back the transaction (maybe because the millionth and one flush threw errors) then all the flushes got rolled back.另一方面,如果您使用的是显式事务,则可以调用一百万次刷新,但如果您回滚事务(可能是因为第百万次刷新引发错误),那么所有刷新都会回滚。

Hope that makes sense.希望这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM