Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do transactions work in nhibernate?

Tags:

c#

orm

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?

like image 363
chobo Avatar asked Jun 05 '11 16:06

chobo


1 Answers

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

like image 155
Baz1nga Avatar answered Oct 05 '22 22:10

Baz1nga