• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Java Third Party Integrations
  • Hibernate
  • Configure Cacheable Objects and Regions
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

Configure Cacheable Objects and Regions in Hibernate Cache

The next step is to configure cacheable objects and regions using either XML Mapping or Hibernate Cache Annotations. After that, edit the ncache-hibernate.xml configuration file as detailed below.

Prerequisites to Configure Hibernate Cache

Please import the following packages to use Jakarta annotations:

  • import jakarta.persistence.*;
  • import org.hibernate.annotations.CacheConcurrencyStrategy;
  • import java.io.Serializable;

Configure Cacheable Objects Using XML Mapping File

Enabling the use of a second level cache does not cache each class's object by default. Instead, classes that need to be cached are marked cacheable as a part of the class mapping (.hbm.xml) file. The following is a sample mapping file orders.hbm.xml of hibernate cache with caching configuration:

<hibernate-mapping package="com.alachisoft.ncache.sample">
    <class name="Orders" table="Orders">
        <cache usage="nonstrict-read-write" region="OrderRegion"/>
        <id name="orderID" type="int">
            <column name="OrderID"/>
            <generator class="assigned"/>
        </id>
        <property name="orderDate" type="date">
            <column name="OrderDate"/>
        </property>
        <property name="shippedDate" type="date">
            <column name="ShippedDate"/>
        </property>
        <property name="shipAddress" type="string">
            <column name="ShipAddress"/>
        </property>
        <property name="shipCountry" type="string">
            <column name="ShipCountry"/>
        </property>
    </class>
</hibernate-mapping>



Members Description
Region Specifies the name of the second-level cache region to use for this class's objects. If no region is specified, a fully qualified class name will be used as the region name with default region configurations.
Usage Specifies caching concurrency strategy to use for this class. Hibernate allows the following three concurrency strategies for caching:
  • read-write
  • nonstrict-read-write
  • read-only
  • Configure Cacheable Objects Using Hibernate Cache Annotations

    Hibernate introduced a new method to define mappings from version 3.5 and onwards. This method acts as a replacement or an addition to the old XML mapping method. This method is known as Hibernate Annotations.

    The following code sample demonstrates how you can use Hibernate Annotations in your hibernate cache.

    @Entity
    @Table(name = "Products")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "ProductRegion")
    public class Product implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ProductID")
        private int productId;
        @Column(name = "ProductName")
        private String productName;
        @Column(name = "SupplierID")
        private int supplierID;
        @Column(name = "CategoryID")
        private int categoryID;
        @Column(name = "QuantityPerUnit")
        private String quantityPerUnit;
        @Column(name = "UnitPrice")
        private double unitPrice;
        @Column(name = "UnitsInStock")
        private int unitsInStock;
        @Column(name = "UnitsOnOrder")
        private int unitsOnOrder;
        @Column(name = "ReorderLevel")
        private int reorderLevel;
        @Column(name = "Discontinued")
        private boolean discontinued;
    
        // Getters
        public int getProductId() {
            return productId;
        }
    
        public String getProductName() {
            return productName;
        }
    
        public int getSupplierID() {
            return supplierID;
        }
    
        public int getCategoryID() {
            return categoryID;
        }
    
        public String getQuantityPerUnit() {
            return quantityPerUnit;
        }
    
        public double getUnitPrice() {
            return unitPrice;
        }
    
        public int getUnitsInStock() {
            return unitsInStock;
        }
    
        public int getUnitsOnOrder() {
            return unitsOnOrder;
        }
    
        public int getReorderLevel() {
            return reorderLevel;
        }
    
        public boolean isDiscontinued() {
            return discontinued;
        }
    
        // Setters
        public void setProductId(int productId) {
            this.productId = productId;
        }
    
        public void setProductName(String productName) {
            this.productName = productName;
        }
    
        public void setSupplierID(int supplierID) {
            this.supplierID = supplierID;
        }
    
        public void setCategoryID(int categoryID) {
            this.categoryID = categoryID;
        }
    
        public void setQuantityPerUnit(String quantityPerUnit) {
            this.quantityPerUnit = quantityPerUnit;
        }
    
        public void setUnitPrice(double unitPrice) {
            this.unitPrice = unitPrice;
        }
    
        public void setUnitsInStock(int unitsInStock) {
            this.unitsInStock = unitsInStock;
        }
    
        public void setUnitsOnOrder(int unitsOnOrder) {
            this.unitsOnOrder = unitsOnOrder;
        }
    
        public void setReorderLevel(int reorderLevel) {
            this.reorderLevel = reorderLevel;
        }
    
        public void setDiscontinued(boolean discontinued) {
            this.discontinued = discontinued;
        }
    
        public Product() {
            // Default constructor required by Hibernate
        }
    }
    



    Annotations Description
    Entity This annotation marks a class as an Entity Bean. This class should at least have a package scope.
    hibernate.annotations.Cache This annotation indicates that the result of invoking a method (or all methods in a class) can be cached.
    Table TThis annotation specifies the details of the database table used to store the entity's data.
    Id The primary key of your Entity Bean is annotated with the @Id annotation. Depending on your table structure, this can either be a single field or a combination of multiple fields.
    GeneratedValue This annotation is used for automatically generating the primary key (@Id) values.
    Column This annotation specifies the properties of the column to which a property or field will be mapped. It has the following attributes:
  • name: Used for explicitly specifying the name of the column.
  • length: Used for specifying the size of the column that has been used to map a value.
  • nullable: Used for specifying a column to be nullable or not based on the generated schema.
  • unique: Used for specifying a column to be unique.
  • See the Hibernate documentation for further details about Hibernate annotations and caching strategies.

    How to Configure Cache Regions

    Hibernate uses cache regions to store objects. NCache allows cache regions to be configured with different properties. For this purpose, NCache has a configuration file named ncache-hibernate.xml, which contains all the region's configurations and other related configurations used by NCache. You can place this file in the root directory of the application or the config folder of the NCache installation directory.

    Following is a sample ncache-hibernate.xml configuration file:

    <configuration>
      <application-config application-id="myapp" enable-cache-exception="true" default-region-name="DefaultRegion" key-case-sensitivity="false">
        <cache-regions>
          <region name="ProductRegion" cache-name="demoCache" priority="BelowNormal" expiration-type="Absolute" expiration-period="8"/>
          <region name="OrderRegion" cache-name="demoCache" priority="Normal" expiration-type="Sliding" expiration-period="8"/>
          <region name="DefaultRegion" cache-name="demoCache" priority="default" expiration-type="None" expiration-period="0"/>
        </cache-regions>
        <database-dependencies>
          <dependency entity-name="Products" type="oledb" sql-statement="SELECT ProductID FROM Products WHERE ProductID ='?';" cache-key-format="Products#[pk]" connection-string="Provider=SQLOLEDB;Data Source=20.200.20.40,1433;Initial Catalog=Northwind;User ID=john;Password=1234;"/>
          <dependency entity-name="Orders" type="oledb" sql-statement="SELECT OrderID FROM Orders WHERE OrderID ='?';" cache-key-format="Orders#[pk]" connection-string="Provider=SQLOLEDB;Data Source=20.200.20.40,1433;Initial Catalog=Northwind;User ID=john;Password=1234;"/>
        </database-dependencies>
      </application-config>
    </configuration>
    

    Theapplication-config section lets you specify the configuration for the use of NCache for a particular application. Multiple application configurations can be specified in ncache-hibernate.xml. Any Hibernate application will use one of the configurations specified based on the application-id in Hibernate's configuration file. Following are the configurable options in the application-config section.

    Members Description
    application-id This option lets you specify the 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, if occurred in NCache, will be propagated to the Hibernate provider.
    default-region-name Allows the user to specify a default region for the application. If a particular region's configurations are not found, the default region's configurations will be used. The specified default region's configuration must exist in the cache-region section.
    key-case-sensitivity This option allows the user to specify whether cache keys will be case-sensitive or not. This option has to be configured according to the database used. If the database is case-sensitive, set this option to true, otherwise false.
    cache-regions This section lets you configure multiple cache regions for the Hibernate 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 region's name should be unique.

    cache-name: This option allows the user to specify NCache's cache name to use for this region.

    priority: The priority you want to use for items cached. The possible values are:

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

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

    expiration-period: This option allows the user to specify the expiration period if absolute/sliding expiration is configured. Its value should be greater than 0. The default units are seconds.
  • database dependencies This section lets you specify database dependencies for the current Hibernate application.

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

    entity-name: Dependencies are added based on the fully qualified class names. This option allows users to specify the class name to which they want to link the current dependency. Any entity can have a maximum of one dependency.

    type: This option allows the user to specify the database dependency type. Possible values are oracle/oledb. Since the NCache provider uses the connection string specified in Hibernate's configuration, use the dependency type appropriate to the connection string.

    sql-statement: Allows the user to specify SQL statements to use for building NCache's database dependency.

    cache-key-format: This option configures the cache-key-format for any item of current entity type. The cache-key format should include "[pk]" in it, which will be replaced with the primary key of the record. It may also include "[en]" which will be replaced with the entity name. The default value of the cache key format is "[en]#[pk]". The same cache key format should be used while writing database triggers in case of OleDb database dependency. See NCache help for writing database triggers for OleDb dependency.

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

    See Also

    Initialize Cache
    Hibernate First Level Cache
    Configure Hibernate Application
    Use Query Caching

    In This Article
    • Prerequisites to Configure Hibernate Cache
    • Configure Cacheable Objects Using XML Mapping File
    • Configure Cacheable Objects Using Hibernate Cache Annotations
    • How to Configure 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