Dashboard > ActiveRecord > ... > How to > Enable second level cache
Enable second level cache
Added by Daniel Rothmaler, last edited by Daniel Rothmaler on Aug 23, 2007  (view change)
Labels: 
(None)


NHibernate, by default, uses a first-level cache, or session-level cache. It means that, inside the same session, you can ask for the same object twice, and the database will be queried just once.

In addition, NHibernate also supports a second-level cache, or sessionfactory-level cache. It can cache object data among different sessions, drastically reducing the need for database queries.

Configuring ActiveRecord to use the second-level cache is quite easy:

Step 1: Configure

Within ActiveRecord configuration:

<config>
  <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
  <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
  <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
  <add key="hibernate.connection.connection_string" value="Data Source=.;Initial Catalog=myapp_db;Integrated Security=SSPI" />

  <add key="hibernate.cache.provider_class" value="NHibernate.Caches.SysCache.SysCacheProvider,NHibernate.Caches.SysCache" />
  <add key="relativeExpiration" value="300" />
</config>

Step 2: Copy necessary assemblies

Reference the assemblies that implements cache support. For the configuration above:

  • NHibernate.Caches.SysCache.dll

Step 3: Enable cache for classes and relations

[ActiveRecord( Cache=CacheEnum.ReadOnly )]
public class Language : ActiveRecordBase 
{
  ...
  [HasMany(.... , Cache=CacheEnum.ReadOnly)]
  ...
  [HasAndBelongsToMany(.... , Cache=CacheEnum.ReadOnly)]
}

Notes

Make sure you understand how NHibernate caching works before enabling this feature. It can become particulary dangerous when your database is changed from outside NHibernate: either manually or by other applications.

Check NHibernate.Caches documentation for more information.

More information

For more information, check NHibernate documentation on enabling the second-level cache.

See also

Site running on a free Atlassian Confluence Community License granted to Castle Project. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.4 Build:#809 Jun 12, 2007) - Bug/feature request - Contact Administrators