Hibernate Cache Levels - First Level Cache

By | | Updated : 2021-03-10 | Viewed : 10947 times

Hibernate Cache Levels - First Level Cache

Performance is a key factor for making the application much comfort to the user world. Usually, every application has a problem with performance. Whenever the application provides quick and fast response then that application makes the user feel much comfort. Hibernate provides the Caching mechanism option to make the application response very fast and better responsive. The current tutorial will describe First Level Cache with example.

Here we will be discussing the types of Hibernate caches and their usage with example. First of all, we need to get familiar with the Cache concept Then we can move on to that Hibernate Cache mechanism.

Cache Introduction:

In general words, Cache refers to the temporary memory. In hibernate, the Cache is also the same kind of temporary memory. To avoid execution(s) of query in database, hibernate has provided this feature. The cache will be resided in between application and database for serving the data.

When Hibernate gets a query from the application for fetching the data, first it will look up into the Cache. If entity(s) exist then the same data entity(s) will be returned to the application. So, in this situation, the Hibernate will not send the query to the database for fetching the records. The Query execution in the database is not required here. Because Cache has the same entity/data. Hibernate will provide the result from the cache, so the time for query execution in the database will be saved. Please refer to the below-given diagram for a better understanding of the Hibernate Cache.

Cache types in Hibernate: As per Hibernate, there are three types of Caches are available for usage in Hibernate.

Cache types

  • First Level Cache

  • Second Level Cache

  • Query Level Cache

First Level Cache:

This is a default cache which is available in the hibernate. No extra configuration is required for enabling the first level cache. After retrieval of the entity from the data store, the same fetched entity’s id will be cached into first level cache by Hibernate. When the Application query again the same entity within the same existed session, the Hibernate will look into the First level cache. If a requested entity exists in First level cache then Hibernate will provide the same entity as a result. So, Data access is not required for getting the result. This is very useful for frequently fetched entity(s) in the same session. The first level cache is associated with the Session. Means cached entity in the first level cache can be only fetched by using the current session. The below-given example will properly explore about this.


  • JdK 11

  • Hibernate 5.4.3

  • 4.11.0

Please create Maven Project as given below.

Create Maven project for Hibernate5-FirstLevelCache-Example
Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values com.docsconsole.tutorials.hibernate5 as Group Id, Hibernate5-FirstLevelCache-Example as Artifact Id 
--> Click on Finish
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">



		<!-- Hibernate 5.4.3.Final -->

		<!-- MySql Driver -->

	<!-- Maven Compiler Plugin -->

Please create java and XML files as shown below for executing the first level cache.

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


		<!-- Database connection settings -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/docsconsole_tutorial</property>
		<property name="connection.username">root</property>
		<property name="connection.password">MyNewPass</property>
		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>
		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<!-- Enable Hibernate's automatic session context management -->
		<property name="current_session_context_class">thread</property>
		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>
		<!-- Drop and re-create the database schema on startup -->
		<property name="hbm2ddl.auto">update</property>
		<mapping resource="com/docsconsole/tutorials/hibernate5/entity/product.hbm.xml" />
package com.docsconsole.tutorials.hibernate5.entity;

public class Product {

	private Integer productId;
	private String productName;
	private String productVendor;

	public Integer getProductId() {
		return productId;

	public void setProductId(Integer productId) {
		this.productId = productId;

	public String getProductName() {
		return productName;

	public void setProductName(String productName) {
		this.productName = productName;

	public String getProductVendor() {
		return productVendor;

	public void setProductVendor(String productVendor) {
		this.productVendor = productVendor;

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"

	<class name="com.docsconsole.tutorials.hibernate5.entity.Product" table="product">

		<meta attribute="class-description">
			This class contains the prodcut details.

		<id name="productId" type="int" column="product_id">
			<generator class="native" />

		<property name="productName" column="product_name" type="string" />
		<property name="productVendor" column="product_vendor" type="string" />


package com.docsconsole.tutorials.hibernate5.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {

		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();

		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
package com.docsconsole.tutorials.hibernate5;

import org.hibernate.Session;

import com.docsconsole.tutorials.hibernate5.entity.Product;
import com.docsconsole.tutorials.hibernate5.util.HibernateUtil;

public class MainClient {

	public static void main(String[] args) {

		try {
			Session session = HibernateUtil.getSessionFactory().openSession();

			Product product = (Product) session.load(Product.class, new Integer(100));

			Product product1 = (Product) session.load(Product.class, new Integer(100));

		} catch (Exception e) {



Please refer below given screenshot for example application for first level cache example.

Hibernate Cache Levels - First Level Cache

After running the example, you will get below given output. Here we are trying to fetch the Product with id 100. You can see the output of MainClient.java file as given below. If you see the console, only one query is getting triggered. Please see the below given screenshot for the same.

Hibernate Cache Levels - First Level Cache
Leave A Reply