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