Open In App

Hibernate - Caching

Last Updated : 27 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Caching in Hibernate is a technique used to store frequently accessed data in memory, reducing database round-trips and improving the performance of applications that use Hibernate as an Object-Relational Mapping (ORM) framework. Hibernate provides two levels of caching: First-Level Cache and Second-Level Cache.

The application interacts with these caches before hitting the database, improving performance and reducing load.

hibernate_caching
Hibernate Caching

1. First-Level Cache

The first-level cache is a session-level cache used by Hibernate.

  • It stores entities that are currently being used by a specific Hibernate session.
  • When an entity is loaded or updated for the first time in a session, it is stored in this cache.
  • Any subsequent request to fetch the same entity within the same session is served from the cache, avoiding a database query.
  • Enabled by default and cannot be disabled.

Example:

Java
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

MyEntity entity1 = session.get(MyEntity.class, 1); // fetched from DB
MyEntity entity2 = session.get(MyEntity.class, 1); // fetched from first-level cache

tx.commit();
session.close();

2. Second-Level Cache

Hibernate also supports a second-level cache, which is a shared cache across multiple sessions.

  • It stores data frequently used across different sessions, reducing database queries.
  • It can be configured with various caching providers such as Ehcache, Infinispan, Hazelcast, JBoss Cache and Caffeine.
  • Unlike the first-level cache, the second-level cache is optional and must be explicitly enabled.

What are the benefits of caching in Hibernate?

  • Improved Performance: Reduces database round-trips by serving data from memory.
  • Reduced Database Load: Minimizes queries, enhancing scalability.
  • Increased Concurrency: Serves multiple requests simultaneously from cache.
  • Customizable: Supports configurable providers, regions, strategies and eviction policies.

Second-level cache providers in Hibernate

Hibernate provides several second-level cache providers that can be used to store cached data in a shared cache across multiple sessions. These include:

  • Ehcache: Efficient in-memory cache with expiration, distributed and persistent caching.
  • Infinispan: Distributed data grid supporting local, replicated and distributed modes with transactions and eviction.
  • Hazelcast: In-memory data grid with partitioning, replication and failover.
  • JBoss Cache: Scalable, distributed and transactional caching.
  • Caffeine: High-performance in-memory cache with fast eviction and async loading.

Developers can also implement custom cache providers using Hibernate’s CacheProvider interface.

How to configure the second-level cache

To configure the second-level cache in Hibernate, you need to perform the following steps:

Step 1: Choose a cache provider

You can choose a cache provider that meets your application requirements. Hibernate provides several cache providers such as Ehcache, Infinispan, Hazelcast, JBoss Cache and Caffeine.

Step 2: Add Provider to Classpath

You need to add the caching provider library to the classpath of your Hibernate application.

Step 3. Configure Hibernate Properties

You need to configure Hibernate properties to enable the second-level cache and specify the caching provider. For example, to enable the Ehcache provider, you can add the following properties to the hibernate.cfg.xml file:

Java
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">
    org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>

Step 4. Configure entity caching

You need to configure entity caching for specific entities in your Hibernate application. You can do this by adding the @Cacheable annotation to the entity class and specifying the cache region name. For example:

Java
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="myEntityCache")
public class MyEntity {
    // ...
}

Step 4. Configure query caching

You can also configure query caching to cache the results of frequently executed queries. You can do this by adding the setCacheable(true) method to the Query object and specifying the cache region name. For example:

Java
Query query = session.createQuery("from MyEntity where name=:name");
query.setParameter("name", "John");
query.setCacheable(true);
query.setCacheRegion("myQueryCache");

How Does Hibernate second-level cache work

  • Request: A session requests an entity or executes a query.
  • Cache Lookup: Hibernate checks if the data is in the second-level cache.
  • Cache Hit: If present, Hibernate returns the data from the cache.
  • Cache Miss: If not present, Hibernate queries the database and stores the result in the cache.
  • Cache Eviction: Updates or deletes automatically remove the corresponding cache entries.
  • Cache Expiration: Entries can expire based on time-to-live or maximum size.

Article Tags :
Practice Tags :

Explore