×
DocsConsole

DocsConsole

Hibernate Cache Tutorial-First Level Cache

By | | Updated : 2019-06-08 | Viewed : 195 times

Hibernate-Cache-Tutorial

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.

    Perquisitions

  • 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
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.docsconsole.tutorials.hibernate5</groupId>
	<artifactId>Hibernate5-FirstLevelCache-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<hibernate-core-version>5.4.3.Final</hibernate-core-version>
		<mysql.connector.version>8.0.12</mysql.connector.version>
	</properties>

	<dependencies>


		<!-- Hibernate 5.4.3.Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate-core-version}</version>
		</dependency>

		<!-- MySql Driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.version}</version>
		</dependency>
	</dependencies>

	<!-- Maven Compiler Plugin -->
	<build>
		<sourceDirectory>src/main/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>11</source>
					<target>11</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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

hibernate.cfg.xml
<?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">

<hibernate-configuration>

	<session-factory>
		<!-- 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" />
	</session-factory>
	
</hibernate-configuration>
Product.java
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;
	}

}
product.hbm.xml
<?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="com.docsconsole.tutorials.hibernate5.entity.Product" table="product">

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

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

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

	</class>

</hibernate-mapping>
HibernateUtil.java
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;
	}
}
MainClient.java
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();
			session.beginTransaction();

			Product product = (Product) session.load(Product.class, new Integer(100));
			System.out.println(product.getProductName());

			Product product1 = (Product) session.load(Product.class, new Integer(100));
			System.out.println(product1.getProductName());

			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

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

Hibernate-Cache-Tutorial-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-Tutorial-First-Level-Cache
Leave A Reply