Cache : First-Level and Second-Level

Author Avatar
Learn Here Fun Pedia
5 min read •
Featured Image

1. First-Level Cache

Let’s learn First-Level Cache and Second-Level Cache from first principles, as this is one of the most important Hibernate interview topics.

1.1 What is a Cache?

A cache is a temporary place where frequently/recently used data is kept so that we don't repeatedly perform an expensive operation. In Hibernate, the expensive operation is a database call:

Java Application
      ↓
Hibernate
      ↓
Database

A database call is avoided when Hibernate already has the required entity in its cache.

1.2 What is First-Level Cache?

First-Level Cache is Hibernate's cache associated with a persistence context. In traditional Hibernate terminology, this persistence context is associated with a Session.

Session / Persistence Context
        |
        ↓
 First-Level Cache
        |
        ├── Employee 101
        ├── Employee 102
        └── Employee 103

The important point is: The first-level cache belongs to the Session/persistence context. It is not shared between different sessions.

1.3 Why does Hibernate need it?

Suppose we execute: Employee e1 = session.find(Employee.class, 101);

Hibernate checks its first-level cache. If it doesn't find Employee 101, it goes to the database, gets the data, puts the entity into the persistence context, and returns it.

1.4 What happens if we request the same entity again?

If we request the same entity within the same session:

Employee e1 = session.find(Employee.class, 101);
Employee e2 = session.find(Employee.class, 101);

The first request hits the database and stores the entity in the L1 cache. The second request checks the L1 cache, finds it, and returns the managed entity, completely avoiding a second DB query.

1.5 & 1.6 Very Important: Same Entity Instance

There's an even deeper reason first-level cache is important. Within the same persistence context, Hibernate maintains one managed entity instance for a given entity identity.

e1 ──────────┐
             ↓
        Employee 101
             ↑
e2 ──────────┘

So, e1 == e2 is true! If Hibernate created two different Java objects representing the same DB row, it could create massive consistency problems. The persistence context acts as both a first-level cache and an identity map.

1.8 Cache Scope

First-level cache has a very limited scope. If Session A loads Employee 101, Session B knows nothing about it. Session B will execute its own database query. First-level cache is not shared between Sessions.

1.10 1 1.11 clear() vs detach() / evict()

If you call session.clear(), Hibernate removes all managed entities from that persistence context. They become detached.

If you only want to remove one specific entity, you use entityManager.detach(employee) (JPA) or session.evict(employee) (Hibernate).

1.12 clear() vs detach() / evict() Table

Operation Effect
clear() Detaches all managed entities.
detach(entity) Detaches one specific entity (JPA standard).
evict(entity) Hibernate-specific way to remove one entity from the Session.

2. Second-Level Cache

Now we move one level higher. The major difference: First-level cache is associated with one persistence context. Second-level cache is associated with the SessionFactory and can be shared across Sessions.

2.1 & 2.2 First-Level vs Second-Level Architecture

              Hibernate
                  |
        ┌─────────┴─────────┐
        ↓                   ↓
     Session A           Session B
        ↓                   ↓
     L1 Cache             L1 Cache
        \                   /
         \                 /
          └───────────────┐
                          ↓
                    L2 Cache
                          ↓
                       Database
  • First-Level Cache: Session-specific (Persistence Context)
  • Second-Level Cache: SessionFactory-level / shared across all sessions

2.4 Cache Regions

Second-level caching can be organized into cache regions for different types of data:

  • Entity Cache: Stores actual entity data (e.g., Employee 101 data).
  • Collection Cache: Stores IDs of collections (e.g., Department 10 -> Employee IDs 101, 102, 103).
  • Query Cache: Stores result identifiers for specific SQL queries.

Note: Query cache and entity cache are different concepts solving different needs!

2.9 Cache Invalidation

This is a major real-world problem. If someone updates the database (salary = 50000), but the cache still holds (salary = 40000), you have a stale cache problem. Caching systems require strategies to invalidate or update data when the underlying database changes.

Final Mental Model Summary

  • L1 Cache: Persistence Context / Session scope.
  • L2 Cache: SessionFactory scope (shared).
  • L1: Fundamental to entity management (identity guarantee, dirty checking).
  • L2: Optional performance optimization.

Important Note: clear(), detach(), and evict() affect the in-memory persistence context state. They DO NOT mean "delete this data from the database." (A common interview trap!)

T3 Interview Questions (FAQs)

Q1. Why is first-level cache mandatory but second-level cache optional?

"First-level cache is associated with the persistence context and is fundamental to Hibernate's entity management. It ensures that within a persistence context Hibernate maintains a managed instance for a given entity identity and supports features such as dirty checking and the unit-of-work pattern. Second-level cache is shared across persistence contexts within the SessionFactory and is primarily a performance optimization. The application can function correctly without it, whereas the persistence-context mechanism relies on first-level caching."

Q2. Does Hibernate never query the database if the entity is in the first-level cache?

This is a trap! It's too broad. The cache primarily avoids loading the same managed entity again through a normal entity lookup (e.g., session.find()). However, other operations like HQL/JPQL queries (e.g., SELECT e FROM Employee e WHERE e.department = :dept) can still cause SQL to execute against the database even if some of those Employee objects are already managed.

Q3. What is the difference between Session Cache and SessionFactory Cache?

Session cache refers to the First-Level Cache, whose scope is a single Session/persistence context. SessionFactory cache refers to the Second-Level Cache, which is shared across all Sessions generated by that SessionFactory.

➔ Read more about Hibernate Column Mapping ➔ Read more about Persistence Context Lifecycle ➔ Read more about Hibernate Entity States ➔ Read more about HQL and JPQL

Comments (0)