• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Show / Hide Table of Contents
  • Programmer's Guide
  • Client Side API Programming
    • Setting Up Development Environment
    • Basic Cache Operations
      • Initialize Cache
      • Add Data to Cache
      • Update Data in Cache
      • Fetch Data From Cache
      • Remove Data From Cache
      • Dispose Cache
    • Bulk Operations
      • Adding Collection to Cache
      • Updating Collection in Cache
      • Retrieving Collection from Cache
      • Removing Collection from Cache
      • Deleting Collection from Cache
    • Asynchronous Operations
      • Using Asynchronous Operations
      • Using Asynchronous Operations with Callback Methods
    • Groups and Subgroups
      • Adding/Updating Data Group in Cache
      • Retrieving Data Group from Cache
      • Removing Data Group from Cache
    • Tagging Data in NCache
      • Creating Tags
      • Adding Items with Tags
      • Retrieving Previously Tagged Data
      • Removing Tagged Items from Cache
    • Named Tags
    • Data Expiration Strategies
      • Using Absolute Expiration
      • Using Sliding Expiration
    • Cache Dependencies
      • Key Dependency
      • File Dependency
      • Notification based Dependencies
        • Database Dependency using SQL Server
        • Database Dependency using Oracle
      • Polling Based Dependency
      • Custom Data Source Dependency
      • Multiple Cache Sync Dependency
      • Aggregate Dependency
      • Add Dependency to Existing Item
      • Using CLR Procedures to Call NCache
    • Locking Data in NCache
      • Locking Items in Cache (Pessimistic Locking)
      • Locking Items with Cache Item Versioning (Optimistic Locking)
    • SQL Reference for NCache
      • SQL Syntax
      • Querying Samples for Operators
      • Querying Data in NCache
      • NCache Language Integrated Query (LINQ)
        • Using LINQ in NCache
        • Configuring LINQPad for NCache
        • Querying NCache Data in LINQPad
    • Event Notifications
      • Cache Level Event Notifications
      • Item Level Event Notifications
      • Custom Event Notifications
    • Publish/Subscribe (Pub/Sub) in NCache
      • Pub/Sub Topics
      • Managing Topics
      • Pub/Sub Messages
        • Message Behavior and Properties
        • Creating a Message
      • Publish Messages to Topic
      • Subscribe for Topic Messages
      • Monitoring Pub/Sub Topics
    • Continuous Query
    • Using Streams in NCache
      • Opening with Stream Modes
      • Adding and Updating Data with Streams
      • Retrieving Data from Streams
      • Closing a Stream
    • Security and Encryption
      • NCache Security
      • NCache Data Encryption
    • Data Compression
    • NCache Management API
  • Server Side API Programming
    • Cache Startup Loader
      • Components of Cache Startup Loader
      • Sample Implementation of ICacheLoader on Single Node
      • Sample Implementation of ICacheLoader with Distribution Hints
    • Data Source Providers (Backing Source)
      • Read-Through Caching
        • Configure Read-Through Provider
        • Using Read-Through with Cache Operations
      • Write-Through Caching
        • Configuring Write-Through Provider
        • Using Write-Through with Basic Operations
        • Using Write-Behind with Basic Operations
        • Using Write-Behind with Bulk Operations
        • Using Write-Behind with Async Operations
        • Monitor Write-Through Counters
    • Custom Dependency
      • Sample Implementation of Custom Dependency
      • Sample Usage of Custom Dependency
    • WAN Replication through Bridge
      • Bridge Configurations
      • Implementing Bridge Conflict Resolver
    • Entry Processor
      • Sample Implementation of IEntryProcessor Interface
      • Sample Usage of EntryProcessor
    • MapReduce
      • Sample Implementation of MapReduce Interfaces
      • Sample Usage of MapReduce
    • Aggregator
      • Sample Implementation of IValueExtractor Interface
      • Sample Implementation of IAggregator Interface
      • Sample Usage of Aggregator
    • Dynamic Compact Serialization
  • Client Side ASP.NET Features
    • ASP.NET
      • ASP.NET Session State Provider for NCache
      • Multi-Region ASP.NET Session State Provider for NCache
    • ASP.NET Core
      • Session Storage in ASP.NET Core
        • Configure NCache ASP.NET Core Session Provider
        • Configure ASP.NET Core Sessions with NCache IDistributedCache Provider
      • Multi-Region ASP.NET Core Session Provider for NCache
      • Object Caching in ASP.NET Core
    • ASP.NET SignalR
      • Using NCache Extension for SignalR
    • View State Caching
      • Configuring and Using Content Optimization
      • Group View State with Sessions
      • Limit View State Caching
      • Perform Page Level Grouping for View State
    • ASP.NET Output Cache
      • Configure ASP.NET Output Caching
      • Using ASP.NET Output Cache with Custom Hooks
  • Client Side Third Party Integrations
    • Migrating AppFabric to NCache
      • AppFabric API vs. NCache API
    • NHibernate
      • NCache as NHibernate Second Level Cache
      • Using NHibernate Query Caching
      • Configuring Database Synchronization with NHibernate
    • Entity Framework Caching Integration
      • NCache as Entity Framework Second Level Cache
      • Entity Framework Caching Config File
    • Entity Framework Core Caching
      • Installing NCache Entity Framework Core Provider
      • Configuring NCache Entity Framework Core Provider
      • Using NCache Entity Framework Core Provider
        • Caching Options for EF Core Provider
        • LINQ APIs for EF Core Provider
        • Cache Only APIs for EF Core Provider
        • Query Deferred APIs for EF Core Provider
      • Logging in NCache Entity Framework Core Provider
    • Memcached
      • NCache Memcached Gateway Approach
      • Memcached Client Plugin for .NET
    • Debug NCache Providers in Visual Studio
    • NCache for Visual Studio Extension

Using NCache as NHibernate Second Level Cache

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

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 second cache in existing NHibernate application without any code change. All that’s needed is to change NHibernate configuration file to plug-in NCache as cache provider and distributed caching can be used.

Second level cache can be configured by enabling the use of second level cache and configuring second level cache provider in NHibernate configurations.

Configuring NHibernate Application to use NCache as 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

  • Place NCache’s NHibernate Provider assembly Alachisoft.NCache.Integrations.NHibernate.Cache.dll located at %NCHOME%/integration/nhibernate/assembly/ in the application's base directory.

  • 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 second level cache in 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 NCache configuration file for NHibernate (NCacheNHibernate.xml). This application id must be specified in application's configuration file (Web.config):

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

Configuring Cacheable Objects

Enabling the use of second level cache does not cache each class object by default. Instead classes needed to be cached are to be marked cacheable in class mapping (.hbm.xml) file. To mark a class cacheable, add the following tag in 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 second level cache region to be used for this class objects. If no region is specified, fully qualified class name will be used as region name with default region configurations.
usage Specifies caching concurrency strategy to be used for this class. NHibernate allows 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 Second Level Cache. This file can be placed at root directory of application or in %NCHOME%/config.

     <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="mycache"
            priority="Default" expiration-type="sliding" expiration-period="180" />
            <region name="default" cache-name="mycache" 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 applications App.config/Web.config file.

    Following are the configurable options in application-config section.

    Member Description
    application-id This option lets the user specify a unique id for current application-config. This id is used to select appropriate configuration for a particular application.
    enable-cache-exception Identifies whether the exceptions if occurred in NCache will be propagated to NHibernate provider.
    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 cache-regions section.
    key-case-sensitivity This option allows to specify whether cache keys will be case sensitive or not. This option has to be configured according to database used. If database is case-sensitive set this option true, otherwise false.
    cache-regions This section lets the user configure multiple cache regions for NHibernate application. Each region's configuration is specified in region tag.
    region This tag contains the configurations for one particular region. Following options can be configured for any particular region.

    name: Each region is identified by its name. 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 options allows to specify type of expiration for any item in this region. Possible values are absolute/sliding/none.

    expiraion-period: Allows to specify 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 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 of classes. This option allows to specify name of class for which current dependency is to be added. Any entity can have maximum one dependency.

    type: Allows to specify database dependency type. Possible values are sql/oracle/oledb. Since NCache provider uses connection string specified in NHibernate's configuration, use dependency type appropriate to 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 cache key format for any item of current entity type. Cache key format should include "[pk]" in it, which will be replaced with the primary key of record. cache-key-format may also include [en] which will be replaced with entity name. Default value of cache key format is"NHibernateNCache:[en] #[pk]. Same cache key format should be used while writing database trigger in case of oledb database dependency.

    composite-key-separator: If the records of current entity have composite key as 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 "$".

    Back to top Copyright © 2017 Alachisoft