This article describes the caching technology in the Hibernate framework. Share it for your reference, as follows:
The cache of the Hibernate framework is divided into Session cache and SessionFactory cache, also known as Level 1 cache and Level 2 cache.
Level 1 cache:
Level 1 cache is a Session-level cache, which has a short life cycle, corresponds to the Session, is managed by Hibernate, and is a transaction-wide cache. When the program calls the Session load() method, get() method, save() method, saveOrUpdate() method, update() method or query interface method, Hibernate will cache the entity object; when the entity object is queryed through the load() method or get() method, Hibernate will first query in the cache. Only when the entity object cannot be found, Hibernate will issue SQL statements to query in the database, thereby improving the efficiency of Hibernate's use.
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(); // Get sessionssion.beginTransaction(); // Enable transaction System.out.println("First query:"); User user = (User)session.get(User.class, new Integer(1));System.out.println("Username:" + user.getName());System.out.println("Second Query:");User user1 = (User)session.get(User.class, 1);System.out.println("Username:" + user1.getName());session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();// An error will roll back the transaction session.getTransaction().rollback();} finally {// Close the Session object HibernateUtil.closeSession(session);}}}When the program first checks the user object through the get() method, Hibernate will issue an SQL statement to query. At this time, Hibernate performs a first-level cache on its user object; when querying through the get() method again, Hibernate will not issue a SQL statement because the user name already exists in the first-level cache. Program running results:
First query: Hibernate: selectuser0_.id as id0_0_,user0_.name as name0_0_,user0_.sex as sex0_0_ fromtb_user_info user0_ whereuser0_.id=?Username: xqhSecond query: username: xqh
Note: The life cycle of the first-level cache corresponds to the Session, and it is not shared between Sessions. In different Sessions, the entity objects cached in other Sessions cannot be obtained.
Level 2 cache:
The second-level cache is a SessionFactory-level cache, and its life cycle is consistent with the SessionFactory. The secondary cache can be shared among multiple sessions, and is a process-wide or cluster-wide cache.
Level 2 Cache is a pluggable cache plug-in, and its use requires the support of third-party cache products. In the Hibernate framework, the usage policy of the secondary cache is configured through the Hibernate configuration file.
1. Add 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 byits value in the running VM.The following properties are translated:user.home - User's home directoryuser.dir - User's current working directoryjava.io.tmpdir - Default temp file path --><diskStore path="java.io.tmpdir"/><!--Default Cache configuration. These will applied to caches programmedly created through the CacheManager.The following attributes are required for defaultCache:maxInMemory - Sets the maximum number of objects that will be created in memoryeternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><defaultCachemaxElementsInMemory="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 theCacheManager startsThe 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 memoryeternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- Sample cache named sampleCache1This cache contains a maximum in memory of 10000 elements, and will expirean element if it is idle for more than 5 minutes and lives for more than10 minutes.If there are more than 10000 elements it will overflow to thedisk 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 sampleCache2This 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 configuration file.
<!-- Enable Level 2 Cache--><property name="hibernate.cache.use_second_level_cache">true</property><!-- Specify cache product provider--><property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property><!-- Specify the entity object to which Level 2 Cache---><class-cache usage="read-only"></class-cache>
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; // First Sessiontry {session = HibernateUtil.getSession();session.beginTransaction();System.out.println("First 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 will roll back the transaction session.getTransaction().rollback();} finally {// Close the Session object HibernateUtil.closeSession(session);} try {session = HibernateUtil.getSession(); // Enable the second cache session.beginTransaction();System.out.println("Second query:");User user = (User)session.get(User.class, 1);System.out.println("Username:" + user.getName());session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();// An error will roll back the transaction session.getTransaction().rollback();} finally {// Close the Session object HibernateUtil.closeSession(session);}}}The secondary cache is shared between sessions, so the same object can be loaded in different sessions. Hibernate will only issue one SQL statement. When the object is loaded the second time, Hibernate will get this object from the cache.
Program results:
First query: Hibernate: selectuser0_.id as id0_0_,user0_.name as name0_0_,user0_.sex as sex0_0_ fromtb_user_info user0_ whereuser0_.id=?Username: xqhSecond query: username: xqh
For L2 cache, some infrequently updated data or referenced data can be used, and its performance will be significantly improved at this time. However, if the frequently changed data is used for L2 cache, performance will cause certain problems.
I hope that the description in this article will be helpful to everyone's Java programming based on the Hibernate framework.