Nhibernate provides 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:
3 Add the mapping of the classes selected as “cacheable” with the following entry:
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 first time than it automatically pushes to the second level cache which is shared by all working process.
Nhibernate L2 Cache Provider Model
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 process on different web servers.
I would recommend the following links if you are interested in incorporating this functionality into your applications: