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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With