Hibernate First Level Cache example using Spring Boot

In this tutorial, we will see Hibernate First Level Cache example using Spring Boot and Oracle. We will cover the below points in Hibernate First Level Cache in this tutorial.

Basic points about Hibernate First Level Cache.

The first level cache is associated with the session object. The data in the first level cache stored as long as the session is open, once the session is closed all data stored in the first level cache would be lost.

The data in the first level cache stored in RAM(In-Memory).

In hibernate, first level cache is enabled by default. No need to do any additional configuration.

Using session.contains() we can know entity exists in cache or not and using session.clear() we can clear the first level cache.

public Student getStudent(int id) {
Session session = entityManger.unwrap(Session.class);
Student studentResponse = session.get(Student.class, id);
System.out.println(session.contains(studentResponse)); // true
session.clear();
System.out.println(session.contains(studentResponse)); // false
return studentResponse;
}

The data stored in the first level cache as the form of key and value pair. There is a map defined in the class where data stores. We will see it later in detail.

private Map<EntityKey, Object> entitiesByKey;

Sample key prepared by hibernate – EntityKey[com.javatute.entity.Student#1]

Sample value – com.javatute.entity.Student@fa7627

Understanding Hibernate first level cache

Consider the scenario, we want to fetch an entity from the database on the basis of id. In the same session for the first time, it will hit the database and it will store the data in the first level cache. Second time onwards if you want to fetch the entity for the same id it will not hit the database, it will get data from first level cache. But make sure still, we are in the same session. Let’s see what does it mean when we say the same session).

Observe the below code snippet.

	public Student getStudent(int id) {
		
		Session session = entityManger.unwrap(Session.class);//line no - 3
		System.out.println("First time record will come from databse");
		Student studentResponse = session.get(Student.class, id);//line no - 5 
		System.out.println("Second time record will come from cache");
		studentResponse = session.get(Student.class, id);//line no - 7
		System.out.println("Third time record will come from cache");
		studentResponse = session.get(Student.class, id);//line no - 9
		System.out.println("Fourth time record will come from cache");
		studentResponse = session.get(Student.class, id);//line no - 11
		session.close();
		return studentResponse;
	}

In the above code snippet, we are trying to fetch the entity from the database using session.get().  Suppose we are passing id(let’s say id 1) from postman or UI. When line number 5  will execute it will hit the real database and store the data into the first level cache. When line number 7, 9, or 11 will execute then it will not hit the real database, it will get data from the first level cache. The code from line number 3 to 11 is in the same session. 

Suppose once again we pass the same id(id 1) from postman or UI then what will happen when the line 5 will execute? Would it hit the real database or get data from the cache? The answer is even we are passing the same id(id 1) it will hit the real database because it is in the different session but while executing line 7, 9, or 11 it will get the data from the cache. We will see this point with an example later in the post.

Understanding Hibernate first level cache

Additionally, when we try to fetch data for the first time(for when line number 5 will execute) first it will check entity is there in first level cache or not. If not then it will check second level cache and if still entity is not there then it will hit the database and get the entity from the database(we will see later in details).

Note – Check Second level cache exmaple using Spring boot.

Spring boot second level cache example using Redis.

Spring boot second level cache example using Hazelcast

Spring boot seocnd level cache example using ehcache.

Hibernate First Level Cache example using Spring Boot and Oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – firstlevelcache, ArtifactId – firstlevelcache and name – firstlevelcache) and click on finish. Keep packaging as the jar.

Modify 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>firstlevelcache</groupId>
	<artifactId>firstlevelcache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>firstlevelcache</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Directory structure –

Hibernate First Level Cache example using Spring Boot

Student.java

package com.javatute.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

StudentController.java

package com.javatute.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.javatute.entity.Student;
import com.javatute.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student save(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Student getStudent(@PathVariable int id) {
		Student studentResponse = (Student) studentService.getStudent(id);
		return studentResponse;
	}

}

Note – See more details about @Controller and RestController here.

StudentRepository.java – interface

package com.javatute.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.javatute.entity.Student;

@Repository
public interface StudentRepository extends CrudRepository<Student, Serializable> {

}

StudentService.java – interface

package com.javatute.service;

import org.springframework.stereotype.Component;

import com.javatute.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);

	public Student getStudent(int id);

}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

StudentServiceImpl.java

package com.javatute.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student response = studentRepository.save(student);
		return response;
	}

	@Transactional
	public Student getStudent(int id) {
		System.out.println("First time record will come from databse");
		Optional<Student> studentResponse = studentRepository.findById(id);
		System.out.println("Second time record will come from cache");
		studentResponse = studentRepository.findById(id);
		System.out.println("Third time record will come from cache");
		studentResponse = studentRepository.findById(id);
		System.out.println("Fourth time record will come from cache");
		studentResponse = studentRepository.findById(id);
		Student student = studentResponse.get();
		return student;
	}

}

SpringMain.java

package com.javatute.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.javatute.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

Note – See more details about @ComponentScan here.

JpaConfig.java

package com.javatute.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.javatute.repository")
public class JpaConfig {

}

Note – See more details about @Configuration annotations here.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091
 
#show sql values
#logging.level.org.hibernate.type.descriptor.sql=trace
 
#hibernate.show_sql = true
#spring.jpa.hibernate.logging.level.sql =FINE
#show sql statement
#logging.level.org.hibernate.SQL=debug

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

http://localhost:9091/student/save

 {
 	"name": "Hiteshdo",
 	"rollNumber": "0126CS01",
 	"university": "rgtu"
 }

Response Data.

{
    "id": 1,
    "name": "Hiteshdo",
    "rollNumber": "0126CS01",
    "university": "rgtu"
}

API -http://localhost:9091/student/{id}

http://localhost:9091/student/1

Hibernate First Level Cache example using Spring Boot

In console we have

Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.roll_number as roll_number3_0_0_, student0_.university as university4_0_0_ from student student0_ where student0_.id=?
Second time record will come from cache
Third time record will come from cache
Fourth time record will come from cache

How First Level Cache internally works in Hibernate.

Till now we have seen some basics about first level cache and its example. We have seen first time when we will try to retrieve the data then it will hit the database next time in the same session or same persistent context it will get the data from first level cache.

In this section, we are going to see how does data stored in the first level cache and how does data retrieved from the first level cache. When we call for first time seesion.get() method first it will prepare key for map(since first level cache data going to store as key and value pair). Suppose we have entity Student.java and we want to get entity for id 1 then sample generated key by the hibernate is as below.

com.javatute.entity.Student#1

Further, the get() method internally calls doLoad() method of org.hibernate.event.internal.DefaultLoadEventListener class. The doLoad() method is defined as below, where the logic has been written to retrieve the data from the fisrt level cache.

	private Object doLoad(
			final LoadEvent event,
			final EntityPersister persister,
			final EntityKey keyToLoad,
			final LoadEventListener.LoadType options) {

		Object entity = loadFromSessionCache( event, keyToLoad, options ); //line no - 7

		if ( entity != null ) {

			return entity;
		}

		entity = loadFromSecondLevelCache( event, persister, keyToLoad );//line no -14
		if ( entity != null ) {
                 //do something print logs

		}
		else {

			entity = loadFromDatasource( event, persister );//line no - 21
		}


		return entity;
	}

Observe the above code snippet. When we call session.get() for the first time, line number 7 and line number 14 both will return null. Since both first level cache and second level cache doesn’t have any cached data. Now line number 21 will execute. The method loadFromDatasource() will internally do a lot of stuff, let’s see some important points here.

  • It will hit the real Database and get the entity for the given id.
  • It will store the entity as the form of key and value pair(Map name is entitiesByKey).
  • It will return the entity.
public class StatefulPersistenceContext implements PersistenceContext {

	private Map<EntityKey, Object> entitiesByKey;

	@Override
	public void addEntity(EntityKey key, Object entity) {
		entitiesByKey.put(key, entity);
	}

	@Override
	public Object getEntity(EntityKey key) {
		return entitiesByKey.get(key);
	}

}

The entitiesByKey map would be initialized as below.

{EntityKey[com.javatute.entity.Student#1]=com.javatute.entity.Student@fa7627}

Here key = com.javatute.entity.Student#1
value = com.javatute.entity.Student@fa7627

Next time when you call session.get() method, the loadFromSessionCache() method will give you the entity from cache for key(com.javatute.entity.Student#1). Let’s have a look into loadFromSessionCache() method.

	protected Object loadFromSessionCache(EntityKey keyToLoad, LoadEvent event) throws HibernateException {

		SessionImplementor session = event.getSession();

		Object old = session.getEntityUsingInterceptor(keyToLoad);
                
		return old;
	}


	@Override
	public Object getEntityUsingInterceptor(EntityKey key) throws HibernateException {

		final Object result = persistenceContext.getEntity( key );
			return result;
		}
	}

When we call session.get() for the first time loadFromSessionCache() method will return null.

When we call session.get() for the second time onwords loadFromSessionCache() method will return cached entity.

Hibernate First Level Cache example using Spring Boot

Note – Here persistenceContext is reference of StatefulPersistenceContext class defined in SessionImpl class. The StatefulPersistenceContext  class implements org.hibernate.engine.spi.PersistenceContext.

StatefulPersistenceContext persistenceContext;

The org.hibernate.engine.spi.PersistenceContext interface referred as first level cache.

The result object line number 14 will contain entity. This is how in first level cache data stores and how we retrieve it.

That’s all about Hibernate First Level Cache example using Spring Boot and Oracle.

You may like.

Other Spring Data JPA and Hibernate tutorials.

Hibernate first level cache docs.

Summary – We have seen about Hibernate first level cache in details. We have seen how data stored in first level cache. The org.hibernate.engine.spi.PersistenceContext interface referred to as first level cache.