NHibernate is a popular Object-Relational Mapping (ORM) framework for .NET applications, which enables seamless database interactions through object-oriented code. However, when applications handle a high volume of transaction loads, they often experience performance bottlenecks due to frequent database queries.
To address this, NHibernate provides Second-Level Caching, which keeps objects in memory at the application level, reducing the need to repeatedly access the database. NCache, an extremely fast and scalable distributed cache, acts as an NHibernate Second-Level Cache provider, which significantly improves application speed, scalability, and reliability.
NCache boosts NHibernate with faster queries, reduced database load, and high-availability as explained below.
Following are some of the key features that NCache offers to NHibernate users:
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default"
key-case-sensitivity="false" >
<cache-regions>
<region name="AbsoluteExpirationRegion"
cache-name="demoCache"
priority="Default"
expiration-type="sliding"
expiration-period="180" />
<region name="default"
cache-name="demoCache"
priority="default"
expiration-type="none"
expiration-period="0"/>
</cache-regions>
</application-config>
</configuration>
<configuration>
<application-config application-id="myapp"
enable-cache-exception="true"
default-region-name="default"
key-case-sensitivity="false">
<database-dependencies>
<dependency entity-name="nhibernator.BLL.Customer"
type="sql"
sql-statement="SELECT ContactName FROM dbo.Customers WHERE CustomerID =?"
cache-key-format="dependency.customer: [us]"/>
</database-dependencies>
</application-config>
</configuration>
This example shows how to enable NHibernate query caching with NCache to store and reuse query results for improved performance.
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customer c")
.SetCacheable(true);
var customers = await query.ListAsync<Customer>();
var newCustomer = new Customer { Name = "John Doe" };
await session.SaveAsync(newCustomer);
await session.FlushAsync();
transaction.Commit();
}
}
Install-Package NHibernate.NCache
Modify your NHibernate configuration files to enable NCache as the second-level cache provider.
Update hibernate.cfg.xml
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="cache.provider_class">
Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider,
Alachisoft.NCache.Integrations.NHibernate.Cache
</property>
<property name="cache.use_second_level_cache">true</property>
</session-factory>
</hibernate-configuration>
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.