Nhibernate Caching

NHibernate provides a default implementation of cache when we use the session object that means if in a single session if you get a single object twice it does not result in two separate queries, this is the first level of cache that NHibernate does as long as you are in a single session.

The First Level Cache is automatically maintained by NHibernate within a transaction when interacting with the database, in this case, it remains in memory. Which can be considered as a short-term cache and is valid only between begin and commit transaction, in isolation from the others.

NHibernate handles it by default, no configuration at all, if for some reason we want to disable or avoid using the cache, we can use a special type of session: StatelessSession, which can be obtained by the method openStatelessSession sessionFactory (). StatelessSession is useful when we have to do massive inserts or updates.

In contrast, the Second Level Cache allows us several steps ahead in improving performance. The fundamental difference is that this type of cache is valid for all transactions and may persist in memory for as long as the application is online, and can be considered as an overall cache.

To enable the Second Level Cache we need to perform the following steps:

1  Select a Cache Provider. I use Ncache.

2  Add the following properties to hibernate configuration file:

  1. <property name=cache.provider_class>
  2.     Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider,
  3.     Alachisoft.NCache.Integrations.NHibernate.Cache
  4. </property>
  5. <property name=cache.use_query_cache>true</property>
  6. <property name=cache.use_second_level_cache>true</property>

3  Add the mapping of the classes selected as “cacheable” with the following entry:

  1. <cache usage=read-write></cache>

Why use second level cache ?

In an Enterprise application, you usually have multiple web servers in a load balance scenario and there are multiple processes running on each of them so it results in placing multiple redundant queries on your database for same data from each working process which slows down your application.

To overcome these problems we can use NHibernate second level cache where NHibernate will get the date from database for the first time. Then it automatically pushes to the second level cache which is shared by all working process.

NHibernate  L2 Cache Provider Model

The cache should be an in-memory cache as u want to increase your application performance.

It needs to be an out of process cache which does not get flushed even if your worker process recycles.

It needs to be distributed so it can be shared among the multiple worker processes on different web servers.

I would recommend the following links if you are interested in incorporating this functionality into your applications:


You might also like