Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Hibernate cache


May 17, 2021 Hibernate


Table of contents


Cache

Caching is an optimization of application performance that reduces the frequency with which applications access physical data sources, thereby improving application performance.

Caching is also important for Hibernate, which uses a multi-level caching scheme as explained below:

Hibernate cache

Level 1 cache

The first-level cache is the Session cache and is a mandatory cache through which all requirements must pass. The Session object, under its own right, saves an object before submitting it to the database.

If you issue multiple updates to an object, Hibernate tries to delay the update as long as possible to reduce the number of SQL update statements issued. If you close session, all cached objects are lost, either saved, or updated in the database.

Secondary cache

The second-level cache is an alternative cache and the first-level cache will always be asked before any object you want to find in the second-level cache. The second-level cache can be installed on top of each class and each collection, and it is primarily responsible for caching objects across sessions.

Any third-party cache can be used with Hibernate. The org.hibernate.cache.CacheProvider interface is provided and must be implemented to provide Hibernate with a cache implementation solution.

Query hierarchical cache

Hibernate also implements a query result set cache that is closely integrated with the second-level cache.

This is a selectable feature and requires two additional physical cache areas that hold cached query results and timestamps from the last update of the form. This is useful only for queries that run frequently with the same parameter.

The second-level cache

Hibernate uses the default first-level cache and you don't have to use a first-level cache. L et's look directly at the optional secondary cache. Not all classes benefit from caching, so it is important to be able to close the secondary cache.

Hibernate's secondary cache is set in two steps. F irst, you must decide which one to use. After that, you use the cache provider to configure cache expiration times and physical cache properties.

The policy of the same

A mediation policy is a mediation that holds data items in the cache and retrieves them from the cache. If you are going to use a secondary cache, you have to decide which side of the policy to use for each persistent class and collection.

  • Transactional: This policy is used for primary read data, and it is critical that a transaction block expired data in a rare case of an update.
  • Read-write: This policy is used again for primary read data, and in the rare case of an update, it is critical that a transaction blocks expired data.
  • Nonstrict-read-write: This policy does not guarantee consistency between the cache and the database. Use this policy if the data barely changes and the expired data is not important.
  • Read-only: A policy for synths that never changes data. Use it only for reference data.

If we're going to use a secondary cache for our Employee class, let's use the read-write policy to add mapping elements that need to be told to Hibernate to cache the Employee instance.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <cache usage="read-write"/>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

The usage-"read-write" parameter tells Hibernate to use read-write a cymbaching policy for the defined cache.

Cache provider

After considering the same policies that you will use for your cache candidates, your next step is to pick a cache provider. Hibernate lets you select a separate cache provider for the entire application.

S.N. The cache name Describe
1 EHCache It can be cached on memory or hard disk and clustered, and it supports the optional Hibernate query result cache.
2 OSCache Supports caching to memory and hard drives in a separate JVM, with rich expiration policies and query cache support.
3 warmCache A JGroups-based aggregate cache. It uses cluster invalidation but does not support Hibernate query caching.
4 JBoss Cache A fully transactional replication cluster cache that is also based on the JGroups multicast library. I t supports replication or failure, synchronous or asynchronous communication, optimistic and pessimistic locking. Hibernate query cache is supported.

Each cache provider is not compatible with each synth policy. The following compatibility matrix will help you choose the right combination.

Policy/provider Read-only Nonstrictread-write Read-write Transactional
EHCache
OSCache
SwarmCache
JBoss Cache

You'll specify .cfg.xml cache provider in the hibernate profile. We chose EHCache as our secondary cache provider:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- Assume students is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      root123
   </property>
   <property name="hibernate.cache.provider_class">
      org.hibernate.cache.EhCacheProvider
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>

Now you need to specify the properties of the cache area. E HCache has its own profile, ehcache .xml, which should be in the application CLASSPATH. The ehcache of the Employee class .xml cache configuration like this:

<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>

That's it, now we have a secondary cache of the Employee class and Hibernate can now hit the cache whether it's when you navigate to Employee or when you upload Employee through an identifier.

You should analyze all your classes for each class and choose the appropriate caching strategy. S ometimes, secondary caching can cause application performance to decline. S o first you don't allow the cache to test your application with a benchmark program, then you turn on the appropriate cache, and then the detection performance is recommended. It doesn't make sense to support any type of cache if the cache doesn't promote system performance.

Query hierarchical cache

In order to use the query cache, you must first activate it hibernate.cache.use_query_cache the "true" property in the configuration file. By setting this property to true, you have Hibernate create the necessary cache in memory to hold the query and identifier set.

Then, in order to use the query cache, you use the setCacheable method of the Query class. For example:

Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
List users = query.list();
SessionFactory.closeSession();

Hibernate also supports very fine-grained cache support through the concept of cache areas. A cache area is the cached portion of the name given.

Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
query.setCacheRegion("employee");
List users = query.list();
SessionFactory.closeSession();

This code uses methods to tell Hibernate to store and look for queries for cached employee regions.