Caching techniques in the Hibernate framework

  • 2020-05-07 19:45:32
  • OfStack

This article illustrates caching techniques in the Hibernate framework. Share with you for your reference, as follows:

The cache of Hibernate framework is divided into Session cache, SessionFactory cache, also known as level 1 cache and level 2 cache.

level 1 cache:

Level 1 cache is an Session cache with a short life cycle, which corresponds to Session and is managed by Hibernate. It is a transaction-scoped cache. When a program calls Session's load() method, get() method, save() method, saveOrUpdate() method, update() method, or query interface method, Hibernate caches the entity object. When entity objects are queried by load() method or get() method, Hibernate will first query in the cache, and Hibernate will issue SQL statement to query in the database when no entity counterpart can be found, thus improving the efficiency of Hibernate.

For example:


package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSession(); //  To obtain session
session.beginTransaction(); // Open the transaction 
System.out.println(" The first 1 Query: ");
User user = (User)session.get(User.class, new Integer(1));
System.out.println(" User name: " + user.getName());
System.out.println(" The first 2 Query: ");
User user1 = (User)session.get(User.class, 1);
System.out.println(" User name: " + user1.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  An error rolls back the transaction 
session.getTransaction().rollback();
} finally {
//  Shut down Session object 
HibernateUtil.closeSession(session);
}
}
}

When the program checks the user object for the first time through get() method, Hibernate will issue an SQL statement to query, and Hibernate will cache its user object at level 1. When queried again using the get() method, Hibernate does not issue the SQL statement because the username already exists in the level 1 cache. Program running results:


 The first 1 Query: 
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
 User name: xqh
 The first 2 Query: 
 User name: xqh

Note: the lifecycle of level 1 cache corresponds to Session, it is not Shared between Session, and the entity objects cached in other Session cannot be obtained in different Session

level 2 cache:

A level 2 cache is an SessionFactory level cache whose life cycle corresponds to SessionFactory1. A level 2 cache can be Shared across multiple Session, either process-scoped or club-scoped caches.

Level 2 cache is a pluggable cache plug-in whose use requires the support of the 3rd party cache product. In the Hibernate framework, the level 2 cache usage policy is configured through the Hibernate configuration file.

1. Join the cache configuration file ehcache.xml


<ehcache>
<!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.
The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/>
<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.
The following attributes are required for defaultCache:
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts
The following attributes are required for defaultCache:
name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->
<!-- Sample cache named sampleCache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.
If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<!-- Sample cache named sampleCache2
This cache contains 1000 elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
<!-- Place configuration for your caches following -->
</ehcache>

2. Set the Hibernate profile.


<!--  open 2 Level cache  -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--  Specify the cache product provider  -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!--  The specified 2 Level cache the entity objects applied to  -->
<class-cache class="com.xqh.model.User" usage="read-only"></class-cache>

Ex. :


package com.xqh.util;
import org.hibernate.Session;
import com.xqh.model.User;
public class Test {
public static void main(String[] args) {
Session session = null; //  The first 1 a Session
try {
session = HibernateUtil.getSession();
session.beginTransaction();
System.out.println(" The first 1 A query :");
User user = (User)session.get(User.class, 1);
System.out.println(" User name: " + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  An error rolls back the transaction 
session.getTransaction().rollback();
} finally {
//  Shut down Session object 
HibernateUtil.closeSession(session);
}
try {
session = HibernateUtil.getSession(); //  Open the first 2 A cache 
session.beginTransaction();
System.out.println(" The first 2 A query :");
User user = (User)session.get(User.class, 1);
System.out.println(" User name: " + user.getName());
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
//  An error rolls back the transaction 
session.getTransaction().rollback();
} finally {
//  Shut down Session object 
HibernateUtil.closeSession(session);
}
}
}

The level 2 cache is Shared between Session, so the same object can be loaded in different Session. Hibernate will issue only one SQL statement. When the object is loaded the second time, Hibernate will fetch the object from the cache.

Program results:


 The first 1 A query :
Hibernate: 
select
user0_.id as id0_0_,
user0_.name as name0_0_,
user0_.sex as sex0_0_ 
from
tb_user_info user0_ 
where
user0_.id=?
 User name: xqh
 The first 2 A query :
 User name: xqh

For a level 2 cache, you can use data that is not frequently updated or referenced and see a significant performance improvement. However, if level 2 caching is applied to frequently changing data, performance can cause a definite problem.

I hope that this article based on the Hibernate framework Java programming help.


Related articles: