How do transactions work in nhibernate?

I just started learning nHibernate and I'm confused about transactions. I know that nhibernate keeps track of all changes to persistent objects in a session, and these changes are sent to the database when committed, but what is the purpose of the transactions?

If I transfer the code to the "using transaction" block and commit commit, does it just commit changes to the object that occurred in the transaction, or does it commit all changes that occurred in the session since the last flash commit?

+7
source share
2 answers

The purpose of transactions is to ensure that you are not running a session with dirty data or an error. Consider a very simple case of a book order transaction.

You are likely to follow these steps: a) Check if the book currently exists. b) Read the customer information and see if he has anything in the shopping cart. c) Update the number of books d) Make an order entry

Now consider the case when you run an error when entering an order, you want your other changes to be undone, and this is when you roll back the transaction.

How do you do this? Well, there are many ways. One way to use web applications is to track the HTTP Error object as follows:

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

Ideally, you should not break your job template with explicit transaction blocks. Try to avoid this as much as possible.

+2
source

If you do not use transactions, then at any time NHibernate sends a batch, which in itself will be a transaction. I'm not sure if session.Flush () is using the package or not. Suppose that it is so. Your first call to session.Flush () will result in a transaction. Suppose your second reset call results in an error. Changes from the first flash will remain in the database.

If, on the other hand, you use an explicit transaction, you can call flush a million times, but if you refuse the transaction (perhaps because a millionth and one flash threw errors), then all flushes are thrown back.

Hope this makes sense.

0
source

All Articles