Enabling NCache in Hibernate Applications
NCache provides a second level or process level distributed cache for Hibernate by implementing CacheProvider and Cache interfaces. You can plug-in NCache to your existing Hibernate application without any code change. Just change your Hibernate configuration file to plug-in NCache as your cache provider and you're all set to start using distributed caching.
Follow these steps to use NCache with Hibernate.
-
Register 'hibernate' and 'ncache' configuration sections in the <configSections> of the web.config or app.config as follows:
<configSections>
<section name = "hibernate-configuration" type = "Hibernate.Cfg.ConfigurationSectionHandler, Hibernate"/>
<section name = "ncache" type = "Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheSection, Alachisoft.NCache.Integrations.Hibernate.Cache"/>
</configSections>
-
Define section details for <hibernate> as follows:
<hibernate-configuration xmlns = "urn:hibernate-configuration-2.2">
<session-factory>
<property name = "cache.provider_class"> Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.Hibernate.Cache </property>
</session-factory>
</hibernate-configuration>
-
Define section details for <ncache> as follows:
<ncache>
<region name = "default">
<add key = "cacheName" value = "mycache"/>
<add key = "enableCacheException" value = "false"/>
<class name = "hibernator.BLL.Customer">
<add key = "priority" value = "1"/>
<add key = "useAsync" value = "false"/>
<add key = "relativeExpiration" value = "180"/> or <add key = "staticExpiration" value = "100"/>
</class>
</region>
</ncache>
The above example of app.config or web.config contains the following options for you to configure. Each of them is explained below as well.
-
useAsync: This is a flag that tells the provider whether to use the standard synchronized "Add" and "Insert" or the asynchronous "AddAsync" and "InsertAsync" operations. The asynchronous operations immediately return control back to the client and queues up the operation in a background queue. Then, a background thread executes the command.
Note:
-
Calling new Configuration() only reads the <hibernate> section.
-
Calling no-parameter version of cfg.Configure() configures Hibernate from app.config if it contains <hibernate-configuration>, otherwise hibernate.cfg.xml is used.
See Also