NH Prof documentation: Transaction and the second level cache

time to read 2 min | 201 words

Another implication of not using explicit transactions with NHibernate is related ot the use of the second level cache.

NHibernate goes to great lengths in order to ensure that the 2nd level cache shows a consistent view of the database. In order to do that it is defering all 2nd level cache updates to the transaction commit. In that way, we can be sure that the data in the 2nd level cache is the one committed to the database.

Forgoing the use of explicit transactions has the effect of nulling the 2nd level cache. Here is an example that would make this clear:

using(var session = sessionFactory.OpenSession()) 
{ 
	var post = session.Get<Post>(1);
	// do something with post
} 

Even if the 2nd level cache is enabled for Post, it is still not going to be cached in the 2nd level cache. The reason is that until we commit a transaction, NHibernate will not update the cache with the values for the loaded entities.

This code, however, does make use of the 2nd level cache:

using(var session = sessionFactory.OpenSession()) 
using(var tx = session.BeginTransaction()) 
{
	var post = session.Get<Post>(1);
	// do something with post
	tx.Commit();
}