Hibernate Caching Mechanism

shape Description

Hibernate Caching Mechanism is to improve the application performance. Hibernate contains two level caches. It will be placed between the application and database, They are Level1 cache and Level2 cache. Following is the brief description about the Hibernate Caching Mechanism that how it works.

Level1 cache in Hibernate

shape Description

Level1 cache is also called Session level Cache which maintains session object. When a session is opened then the cache opens automatically.

If one performs any Database operations then they can create a session object. Session connection is automatically opened and closed in Hibernate using get(). It goes to Level1 cache and checks for objects, if an object already exists in Database, then it reads the object from Level1 cache else, reads objects from database and stores it in Level1 cache, and then reads the object from the database.

shape More Info

Session object can be created N-number of times. But, it can’t maintain entire application. With the help of cache, hibernate will improve the performance of an application by reducing the number of round trips between application and database. From a level1 cache, one can remove a particular object and can call evict() of session interface.

shape Example

For example, Employee table containing id and name property, remove one class object and call evict().

Employee employee=new Employee();
employee.setEmployeeId(3);
session.evict(employee);

Level2 Cache

shape Description

Level2 cache object maintains SessionFactory. This object containes entire application. But, it should be enabled explicitly.

Level2 Cache implementations are provided by different vendors such as.


Every implementation provides the different cache usage functionality.

shape Uses

Level2 cache is used in different ways.

The cache tag is defined under the class tag in mapping file. In Configuration file, add the cache property.


<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>
<property name=”hibernate.cache.use_second_level_cache”>true</property>  

Add the persistance class in ehcache.xml.

<ehcache>   
<class name=”persistence class” maxElementsInMemory=”300”external=”false”timeToldleSeconds=”5”timeToLiveSeconds=”200”/>
</ehcache>

maxElementsInMemory defines count of session object creation and time taken to create.

Using the Level2 Cache, read one object for multiple times, then Hibernate will create a query in command prompt or console.

Level2 cache

shape Example

Employee.java

public class Employee {
private int id;
private String name;
private float salary;
public Employee() {
	super();
}

public Employee(String name, float salary) {
	super();
	this.name = name;
	this.salary = salary;
}

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 float getSalary() {
	return salary;
}
public void setSalary(float salary) {
	this.salary = salary;
}
}

Here the developer created the class Employee and also created the constructor to the Employee. Employee class has variables such as Name, id, salary. Set and Get methods are used on the variables.
FetchTest.java

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

public class FetchTest {
public static void main(String[] args) {
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
	
	Session session1=factory.openSession();
	Employee emp1=(Employee)session1.load(Employee.class,121);
	System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
	session1.close();
	
	Session session2=factory.openSession();
	Employee emp2=(Employee)session2.load(Employee.class,121);
	System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
	session2.close();
	
}
}

Application acquires session objects from Session Factory. SessionFactory is for the most part arranged as Singleton in application, SessionFactory stores produce SQL statements and other mapping metadata that Hibernate utilizes at runtime.
StoreTest.java

import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreTest {
public static void main(String[] args) {
	Session session=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
	
	Transaction tx=session.beginTransaction();
	
	session.persist(new Employee("Rahul",50000));
	session.persist(new Employee("Ajay",70000));
	
	tx.commit();
	session.close();
}
}

The save and persist methods are used to persevere the transient object. Save and persist strategy comes about a SQL insert query. On the off chance that any properties are overhauled after the save or persist strategy and before the transaction is conferred or session is flushed, the progressions will be spared to the database utilizing update query.
employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>   
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
 <hibernate-mapping>    
 <class name="com.javatpoint.Employee" table="emp1012">    
 <cache usage="read-only" >    
 <id name="id&quot;>    
 <generator class="native"></generator>   
 </id>    
 <property name="name"></property>   
 <property name="salary"></property>    
 </class>   
     
 </hibernate-mapping>
 

hibernate.cfg.xml


<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN” http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>  
<!-- Generated by MyEclipse Hibernate Tools.    
<hibernate-configuration>  
 <session-factory>    
 <property name=”show_sql”<true</property>    
 <property name=”hbm2ddl.auto”<update</property>   
 <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>   
 <property name=”connection.url”<jdbc:mysql://localhost:3306/test_db</property>    
 <property name=”connection.username”>root</property>   
 <property name=”connection.password”<root</property>    
 <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>  
 <property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>   
 <property name=”hibernate.cache.use_second_level_cache”<true</property>    
     
 <mapping resource=”employee.hbm.xml”/>
 </session-factory>
</hibernate-configuration>
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.

ehcache.xml

<?xml version="1.0"?>   
<ehcache>  
<defaultCache maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="200" />    
<cache name="com.javatpoint.Employee" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />  
</ehcache>

Output:

Details of an employee should given as static in the database with an ID of 121 as mentioned in the code.

Final output will be as follows.

Summary

shape Key Points

  • Hibernate Caching Mechanism – EHcache is the hawker of second level cache implementation.
  • Hibernate Caching Mechanism – <cache usage=”read only”/>is the cache element will be used in mapping file.
  • First level cache will be enabled by default.