Hibernate First Level Cache with Example

The first level cache in hibernate is enabled by default and you can not disable it. The First level cache is associated with the Session object.

Similarly, first-level cache available only till the session object exists. It is available to session object only and is not accessible to any other session object in any other part of the application.

Maven dependencies

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.20.Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency>

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"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">org.h2.Driver</property> <property name="hibernate.connection.url">jdbc:h2:mem:test</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create-drop</property> <mapping class="com.javacodestuffs.hibernate.entity.Student"></mapping> <mapping class="com.javacodestuffs.hibernate.entity.Address"></mapping> <property name="hibernate.current_session_context_class">thread</property> </session-factory> </hibernate-configuration>

package com.javacodestuffs.hibernate.util; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { private static SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { if (sessionFactory == null) { StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build(); Metadata metaData = new MetadataSources(standardRegistry) .getMetadataBuilder() .build(); sessionFactory = metaData.getSessionFactoryBuilder().build(); } return sessionFactory; } catch (Exception ex) { System.out.println("Execption occured during session factory creation"+ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } }

First level cache example

//Open the hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); //fetch the address - first get Address address = (Address) session.load(Address.class, new Integer(1)); System.out.println(address.getCity()); //fetch the address - second get address = (Address) session.load(Address.class, new Integer(1)); System.out.println(address.getCity()); session.getTransaction().commit(); HibernateUtil.shutdown();

Removing cache objects from the first level cache

We can remove some of the objects from the first level cache when needed. Hibernate provides 2 methods to do this.

 evict()
clear()

evict() : It is used to remove a particular object from the cache associated with the session.

clear() : It is used to remove all cached objects associated with the session. So they are essentially like remove one and remove all.

//Open the hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); try { //Open the hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); //fetch the address - first get Address address = (Address) session.load(Address.class, new Integer(1)); System.out.println(address.getCity()); //fetch the address - second get address = (Address) session.load(Address.class, new Integer(1)); System.out.println(address.getCity()); session.evict(address); //session.clear(); address = (Address) session.load(Address.class, new Integer(1)); System.out.println(address.getCity()); } finally { session.getTransaction().commit(); HibernateUtil.shutdown(); }

In this article, we have seen Hibernate First Level Cache with Example.