Hibernate Caching

Hibernate caching It is a mechanism to increases the performance of application by storing or cache objects.

Cache stores data which is not dynamic or doesn’t going to change for longer time of period. e.g. list of countries and states.

There are two type of caching:
1. First level cache
2. Second level cache

First Level Cache

It is a required cache by default enabled by Hibernate. As part of first level cache, all objects gets store in session.

Application can have multiple sessions. Data didn’t get share in between sessions.

first level cache is mandatory and can not be disabled.

Example

Below is a very important example to understand how cache works to reduce performance.

If we see the above example, we are reading user id 5 at line number 33, and in the output it is running a query and getting the data because there is no cache because we are running this query for the first time.

Now, at line 38, we are retrieving user id 6, who is also running a query and retrieving a record from the database because it is not present in memory for the same reason that we are retrieving user id 6 for the first time.

Now, we have fetched the user with id 5 and 6.

Again, running a query at line number 5 is running a Hibernate query and fetching the record directly from the database. Why is it doing the same? As a result, we terminate the session at line 35 for that user with the ID of 5.The object or record will be removed from the cache or session using evict().

At line numbers 44 and 47, we are again trying to fetch the user from database. But, this time it didn’t run the query to get the result directly from the database. If the object was obtained from a session or cache and the record was returned before reaching the database. Reading an object from session saved our time and improved performance as we saved one call to hit database and fetch data.

There are some other methods also to clear cache as mentioned below:

session.evict(): Remove objects from cache/session

session.refresh(): It will refresh the cache.

session.clear(): This method will remove all objects from the cache / session.

Second Level Cache

First level cache gets enable by default. But, on the other hand second level cache required some configuration to gets enable. Second level cache can be access by application.

Sessions can access SessionFactory objects. The data will get automatically wiped out once SessionFactory is closed.

Whenever we trigger a query to get data. First, it will always check into first level cache. If not found, it will look into 2nd level cache.

Below steps are required to enable second level cache:

1. Set second level cache as true and add the cache provider:

2. Add ehcach.xml and its content as mentioned in below screenshot.

3. Declare caching type by adding @Cache annotation with concurrency strategy.

Below are the cache concurrency strategies provided by Hibernate.

CacheConcurrencyStrategy.NONE
CacheConcurrencyStrategy.READ_ONLY
CacheConcurrencyStrategy.NONSTRICT_READ_WRITE
CacheConcurrencyStrategy.READ_WRITE
CacheConcurrencyStrategy.TRANSACTIONAL

Below code will help us to know the statistics or count for first and second level cache hint.

Query Level Cache

It helps us to cache queries results.

Query Level cache is require to enable per bean class. Below line need to be added to enable query cache in hibernate.cfg.xml file.

Enable query cache after setting it as true as shown below.

Cache Over all Architecture

This architecture will help us understand the query and result-response flow.

It will first check results in the first-level cache every time hibernate query gets triggered. If not found, it will look in the second-level cache. At last, It will look in the database if it is not found in the second-level cache also.

Returning back response from database, first it will get store in second level cache and than it will get store in first level cache and then in last it will return the result.

If query results are discovered in the second-level cache, Before returning the response, it will first save it in the first-level cache.

Cache Provider

Below are the common cache provider to store or cache second level objects:

1. EHCache (Easy Hibernate Cache): It has a capability to save data in RAM and ROM.

2. OSCache (Open Symphony Cache): It is mainly used for clustering via either JavaGroups or JMS

3. Swarm Cache (): Its mainly supports more and more read operations.

4. JBoss Cache: This is read only and used for tansanctions only.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan