Cookie Consent by Free Privacy Policy Generator NHibernate Second Level Cache - NCache

NHibernate Second Level Cache

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.

Why Use NCache as NHibernate Second-Level Cache?

  • Performance: Storing frequently accessed data in-memory reduces database trips, leading to faster query execution and improved application responsiveness.
    • Client Cache: NCache supports Client Cache, allowing applications to access frequently used data, reducing network calls and further enhancing performance.
    • Compact Serialization: NCache ensures efficient serialization and deserialization with Compact Serialization, making data retrieval significantly faster than standard .NET serialization.
  • Linear Scalability: NCache allows applications to scale dynamically by adding more cache servers and ensuring the cache load is evenly distributed in a clustered environment.
  • High Availability: NCache's Peer-to-peer clustering eliminates downtime, while automatic failover & replication prevent data loss and maintain cache consistency. NCache offers intelligent data replication through multiple caching topologies, including:
    • Partition-Replica Cache: Maintains redundant copies of cached data across partitions to prevent data loss.
    • Mirrored Cache: Provides a synchronous backup mechanism for real-time failover.
    • Replicated Cache: Ensures data availability by distributing the same cache across multiple nodes in the cluster.

Key Features of NCache for NHibernate

No Code Change Required

  • Easily integrates with NHibernate as a plug-and-play solution without modifying existing application code.
  • All configurations are managed through XML-based configuration files.

Multiple Cacheable Regions

  • Cache Item Priority: Assign different priority levels (High, Normal, Low) to cached data, ensuring frequently accessed objects stay in the cache longer.
  • Absolute Expiration: Cache entries expire at a fixed time, automatically removing outdated data.
  • Sliding Expiration: Expiration resets upon access, making it ideal for frequently used but dynamic data.
  • Region-Based Configuration: Customize caching behavior for different data region using the NCacheNHibernate.xml configuration file.
<configuration>
  <application-config application-id="myapp"
                      enable-cache-exception="true"
                      default-region-name="default">
    <cache-regions>
      <region name="default"
              cache-name="mycache"
              priority="default"
              expiration-type="absolute"
              expiration-period="300" />
    </cache-regions>
  </application-config>
</configuration>

Database Synchronization

  • Monitors database changes to keep cached data up to date.
  • Works seamlessly with SQL Server, Oracle, and OLEDB-based databases.
  • Uses SQL dependency-based invalidation to remove or refresh stale cached data.
<configuration>
  <application-config application-id="myapp"
                      enable-cache-exception="true">
    <database-dependencies>
      <dependency entity-name="Orders"
                  type="sql"
                  sql-statement="SELECT OrderID FROM Orders WHERE OrderDate > GETDATE()-1"
                  cache-key-format="dependency.order:[OrderID]" />
    </database-dependencies>
  </application-config>
</configuration>

NHibernate Query Cache

  • Query Result Caching: Caches query results to reduce repeated executions of the same database queries.
  • Query Storage: Stores queries in the NHibernate.QueryCache region for faster lookups.
  • Async Operations: Updates the cache non-blocking matter, ensuring that application execution is not delayed.
  • Sync Operations: Instantly updates or invalidates cached data when database changes occur, maintaining data consistency.

Enable Query Caching in Application Code:

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();
    }
}

How to Configure NCache with NHibernate?

Install NCache Client for NHibernate

  • Install the NCache NHibernate Provider via NuGet:
    Install-Package NHibernate.NCache

Install NCache Server

  • Download and install NCache.
  • Configure distributed cache clusters for high availability.

Configure NCache for NHibernate

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>
    <property name="cache.use_query_cache">true</property>
  </session-factory>
</hibernate-configuration>

What to Do Next?

© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.