简体   繁体   中英

How do transactions work in nhibernate?

I just started learning nHibernate and I'm confused by transactions. 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?

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?

The purpose of transactions is to make sure that you dont commit a session with dirty data or error on it. 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. b) Read the customer details and see if he has anything in the shopping cart. c) Update the book count d) Make an entry for the order

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:

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. I'm not sure if the session.Flush() uses a batch or not. Let's suppose it does. Your first call to session.Flush() would result in a transaction. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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