Friday, March 23, 2007

NHibernate First and Second Level Cache

One of the more powerful features of NHibernate is the ability to cache object data in memory. This feature provides software developers with the means to create faster more responsive applications. NHibernate provides software developers with two levels of cache the first level cache and the second level cache.

First Level Cache


By default NHibernate uses a first Level Cache. The first level cache is located on the session level. Requests for the same object will query the database only once. In a typical NHibernate application one would do the following:


  1. Obtain a session object form the session factory.
  2. Start a transaction. ISession.BeginTransaction()
  3. Perform a CRUD(create, retrieve, update, delete) operation using the session object.
  4. Close the session object. ISession.Close().
Inorder to use the cache we must request the same object in step 3 before the session is closed. The following will demonstrate the use of the first level cache.


  1. Obtain a session object form the session factory.
  2. Start a transaction. ISession.BeginTransaction()
  3. Retrieve object with ID=1. The object is retrieved from the database.
  4. Retrieve object with ID=1. The object is retrieved from the cache.
  5. Close the session object. ISession.Close()
  6. Obtain a session object from the session factory.
  7. Start a transaction. ISession.BeginTransaction()
  8. Retrieve object with ID=1. The object is retrieved from the database
  9. Close the session object. ISession.Close()
Second Level Cache

The second level cache is optional. The second level cache is located at the Session Factory level. The second level cache can cache object data from different sessions. This means that all session objects can access the same cached data. The intended purpose of the second level cache is to make a good application better. The second level cache should not be used as solution to increase the speed of an under preforming application. NHibernate supports the use of different cache providers. According too NHibernate 1.2 documentation three cache providers are provided hashtable cache, asp.net cache and prevalence cache.

For more information please visit the Hiberbate website.

1 comments:

Sarah on Nhibernate Cache said...

Thanks for mentioning the various options that you have for second level Nhibernate Cache. Just wanted to point out that NCache is a great second level caching option for NHibernate users. Check it out.

Cheers!