• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • .NET Third Party Integrations
  • NHibernate
  • Second Level Cache
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

Second-level NHibernate Cache

NHibernate has a first-level or session-level cache which is used by default. Each session contains its session-level cache which is not shared with other sessions. This cache is disposed of whenever the session is closed. However, NHibernate allows to use second-level, across the session cache which spans across the session's lifetime and can be shared by multiple sessions.

Note

This feature is also available in NCache Professional.

NCache provides a second-level or process-level cache for NHibernate by implementing NHibernate's ICacheProvider and ICache interfaces. This enables NCache to be used as NHibernate's second cache in existing NHibernate applications without any code change. All that is required is to change the NHibernate configuration file to plug in NCache as a cache provider.

The Second-level Cache can be configured by enabling it and configuring a Second-level Cache provider in NHibernate configurations.

Configuring NCache as Second-level Cache

Important

Use NHibernate Version 2.2.3 to use NCache as NHibernate Second-level Cache.

Create NHibernate region in Web.config

Add the <hibernate-configuration> in Web.config under the <configSections> tag:

<configSections>
  <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

Specify Configurations for NHibernate Region

  • Install NCache NuGet package for application without NCache installation. Execute any of the following commands in Package Manager Console inside Visual Studio:

    • For Enterprise:
      Install-Package NHibernate.NCache
    • For Profesional:
      Install-Package NHibernate.NCache.Professional
    • For Open Source:
      Install-Package NHibernate.NCache.OpenSource
  • Configure NCache as NHibernate's Second-level Cache Provider by adding the cache.provider_class property under the specified region (<hibernate-configuration>).

  • Enable the use of a Second-level Cache in the application by setting the cache.use_second_level_cache property to True.

<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>

Specify Application ID for NCache NHibernate Provider

NCache Provider for NHibernate identifies each application by an application-id. This ID is used to find the appropriate configuration for that application from the NCache configuration file for NHibernate (NCacheNHibernate.xml). This application-id must be specified in the application's configuration file (Web.config):

  <appSettings>
    <add key="ncache.application_id" value="myapp" />
  </appSettings>

Configuring Cacheable Objects

Enabling the use of a Second-level Cache does not cache each class object by default. Instead, classes that need to be cached are to be marked cacheable in the class mapping (.hbm.xml) file. To mark a class cacheable, add the following tag in the class's configuration:

<cache usage="read-write" region ="AbsoluteExpirationRegion"/>

In the above tag, properties usage and region can be changed.

Members Description
region Specifies the name of the Second-level Cache region to be used for this class object. If no region is specified, a Fully Qualified Name (FQN) will be used as a region name with default region configurations.
usage Specifies caching concurrency strategy to be used for this class. NHibernate allows the following three concurrency strategies to be used for caching:
  • Read-Write
  • Nonstrict-Read-Write
  • Read-Only
  • Configuring Cache Regions

    NHibernate uses cache regions to store objects. NCache allows NHibernate cache regions to be configured with different properties. For this purpose, NCache has a configuration file named NCacheNHibernate.xml, which contains all regions’ configurations used by NHibernate's Second-level Cache. This file can be placed in the root directory of the application or in %NCHOME%\config (Windows) or /opt/ncache/config (Linux).

     <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>
    

    Multiple application configurations can be specified in NCacheNHibernate.xml. Any NHibernate application will use one of the specified configurations based on the application-id specified in the application's App.config/Web.config file.

    The following are the configurable options in the application-config section.

    Member Description
    application-id This option lets the user specify a unique id for the current application-config. This ID is used to select the appropriate configuration for a particular application.
    enable-cache-exception Identifies whether the exceptions that occurred in NCache will propagate to NHibernate provider or not.
    default-region-name Allows to specify a default region for the application. If a particular region's configurations are not found, default region configurations will be used. Specified default region configuration must exist in the cache-regions section.
    key-case-sensitivity This option allows you to specify whether cache keys will be case-sensitive or not. This option has to be configured according to the database used. If a database is case-sensitive, set this option to True, otherwise, False.
    cache-regions This section lets the user configure multiple cache regions for the NHibernate application. Each region's configuration is specified in the region tag.
    region This tag contains the configurations for one particular region. The following options can be configured for any particular region.

    name: Each region is identified by its name. The name of the region should be unique.

    cache-name: This option allows specifying NCache’s cache name to be used for this region.

    priority: The priority the user wants to use for cached items. The possible values are

  • Default
  • Low
  • BelowNormal
  • Normal
  • AboveNormal
  • NotRemovable

  • expiration-type: This option allows to specify the type of expiration for any item in this region. Possible values are absolute/sliding/none.

    expiration-period: Allows specifying expiration period if absolute/sliding expiration is configured. Its value should be greater than 0.

    database-dependencies It lets the user specify database dependencies for the current NHibernate application.

    dependency: Each dependency is configured in a dependency tag. Multiple tags can be configured for multiple dependencies. The following options can be configured for each dependency.

    entity-name: Dependencies are added based on the Fully Qualified Name (FQN) of classes. This option allows to specify the name of the class for which the current dependency is to be added. Any entity can have a maximum of one dependency.

    type: Allows to specify the database dependency type. Possible values are SQL/Oracle/OleDB. Since the NCache provider uses a connection string specified in NHibernate's configuration, use a dependency type appropriate to the connection string.

    sql-statement: Allows to specify SQL statement to be used for building NCache's database dependency.

    cache-key-format: This option is used to configure the cache key format for any item of the current entity type. The cache key format should include "[pk]" in it, which will be replaced with the primary key of the record. cache-key-format may also include [en] which will be replaced with the entity name. The default value of the cache key format is NHibernateNCache:[en] #[pk]. The same cache key format should be used while writing database triggers in case of OleDB Database Dependency.

    composite-key-separator: If the records of the current entity have a composite key as a primary key, Cache-key is formed by combining all keys separated by composite-key-separator. Composite-key-separator must be of one-character length. Its default value is "$".

    See Also

    Using NHibernate Query Caching
    Configuring Database Synchronization with NHibernate
    Entity Framework Cache Provider

    In This Article
    • Configuring NCache as Second-level Cache
      • Create NHibernate region in Web.config
      • Specify Configurations for NHibernate Region
      • Specify Application ID for NCache NHibernate Provider
    • Configuring Cacheable Objects
    • Configuring Cache Regions
    • See Also

    Contact Us

    PHONE

    +1 (214) 764-6933   (US)

    +44 20 7993 8327   (UK)

     
    EMAIL

    sales@alachisoft.com

    support@alachisoft.com

    NCache
    • NCache Enterprise
    • NCache Professional
    • Edition Comparison
    • NCache Architecture
    • Benchmarks
    Download
    Pricing
    Try Playground

    Deployments
    • Cloud (SaaS & Software)
    • On-Premises
    • Kubernetes
    • Docker
    Technical Use Cases
    • ASP.NET Sessions
    • ASP.NET Core Sessions
    • Pub/Sub Messaging
    • Real-Time ASP.NET SignalR
    • Internet of Things (IoT)
    • NoSQL Database
    • Stream Processing
    • Microservices
    Resources
    • Magazine Articles
    • Third-Party Articles
    • Articles
    • Videos
    • Whitepapers
    • Shows
    • Talks
    • Blogs
    • Docs
    Customer Case Studies
    • Testimonials
    • Customers
    Support
    • Schedule a Demo
    • Forum (Google Groups)
    • Tips
    Company
    • Leadership
    • Partners
    • News
    • Events
    • Careers
    Contact Us

    • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

    • Contact Us
    •  
    • Sitemap
    •  
    • Terms of Use
    •  
    • Privacy Policy
    © Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
    Back to top