Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Transactions on Reads

I have read the documentation and explanation on why it is highly recommended to use transactions on read operations in NH. However, I still haven't totally "bought" into it yet. Can someone take a stab at explaining it without just telling me to RTFM, which I have already done? ;)

like image 973
Bob Avatar asked Nov 01 '09 15:11

Bob


People also ask

What is transaction NHibernate?

NHibernate is not itself a database. It is a lightweight object-relational mapping tool. Transaction management is delegated to the underlying database connection. If the connection is enlisted with a distributed transaction, operations performed by the ISession are atomically part of the wider distributed transaction.

What does NHibernate flush do?

An nHibernate session maintains all changes to the object model. At some point, it needs to synchronize these changes with the database.


2 Answers

This post from one of the authors might have your answer:

Even if we are only reading data, we want to use a transaction, because using a transaction ensure that we get a consistent result from the database. NHibernate assume that all access to the database is done under a transaction, and strongly discourage any use of the session without a transaction.

Leaving aside the safety issue of working with transactions, the assumption that transactions are costly and we need to optimize them is a false one. As already mentioned, databases are always running in transaction. And databases have been heavily optimized to work with transactions. The question is whatever this is per statement or per batch. There is some amount of work that need to be done to create and dispose a transaction, and having to do it per statement is actually more costly than doing it per batch.

like image 182
Chris S Avatar answered Sep 20 '22 11:09

Chris S


What the others have said is true, but they've not pointed out that the problem with not controlling transactions yourself is that if you perform several NHibernate operations without an explicit transaction, each of these operations will take place in separate transactions.

So you can easily get inconsistency between the operations. By explicitly starting an NHibernate transaction then performing the operations in it, you're guaranteed consistency across these operations.

This is, of course, true for ANY data access layer that implicitly starts transactions for you if you do not. It's not limited to NHibernate.

like image 26
Mike Scott Avatar answered Sep 17 '22 11:09

Mike Scott