Spring Boot – JPA First Level Cache (Persistence Context)

 


Spring Boot – JPA First Level Cache (Persistence Context)

Core Concept (from PDF)

  • First Level Cache = Persistence Context
  • It is enabled by default in JPA/Hibernate.
  • It is scoped to EntityManager.
  • Every EntityManager maintains its own cache.

If an entity is already present in Persistence Context, JPA will not hit the database again.


Flow shown in PDF

1. During Application Startup

JPA creates:

  • Database
  • Tables automatically (because of ddl-auto=create)

2. Insert and Read Scenario

Even if you:

  1. Insert data
  2. Then read it multiple times

👉 Only one SELECT query goes to DB.

All further reads come from first level cache.


Important Observation (from logs in PDF)

Only one SQL:

select * from user_details where id=1;

After that:

  • No SQL
  • Data served from memory

Persistence Context Scope

From PDF:

PersistenceContext is associated with EntityManager

So:

  • Same HTTP request → Same EntityManager → Cache works
  • New request → New EntityManager → Cache lost

EntityManager Example (from PDF)

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

User u1 = em.find(User.class, 1L);
User u2 = em.find(User.class, 1L);

em.getTransaction().commit();

Output:

  • Only one DB hit
  • Second find() uses cache

DispatcherServlet Insight (from PDF)

Spring internally:

  • Creates one EntityManager per request
  • Injects same instance into:
    • Service
    • Repository
    • DAO

So inside same request:

Cache always works


Extra Notes (Not directly in PDF but important)

1. Cache States of Entity

State Meaning
New Not yet persisted
Managed In persistence context
Detached EntityManager closed
Removed Marked for delete

Only Managed entities are cached.


2. When Cache is Lost?

Cache is cleared when:

  • EntityManager is closed
  • Transaction ends
  • New HTTP request

3. Methods that BYPASS First Level Cache

Method Behavior
clear() Clears entire cache
detach(entity) Removes one entity
refresh(entity) Forces DB hit
Native query Bypasses cache

4. First vs Second Level Cache

Feature First Level Second Level
Scope EntityManager Application
Default Yes No
Memory Per request Shared
Config needed No Yes (Ehcache/Redis)

Real Interview Q&A

Q1. What is First Level Cache?

Answer:
First level cache is the default cache mechanism in JPA, where entities are stored in the persistence context associated with EntityManager.


Q2. Is first level cache shared?

Answer:
No. It is not shared between EntityManagers.


Q3. When does DB get hit again?

Answer:
When:

  • New EntityManager is created
  • Entity is detached
  • Cache is cleared
  • Transaction ends

Q4. Does repository use same EntityManager?

Answer:
Yes. Spring injects the same EntityManager per HTTP request.


Q5. Does save() store in cache?

Answer:
Yes. After save() entity becomes managed and stays in cache.


Q6. Is first level cache configurable?

Answer:
No. It is mandatory and cannot be disabled.


One-Liner for Interview

First level cache is the persistence context of JPA, scoped to EntityManager, and ensures that within the same transaction/request, the same entity is never fetched twice from the database.


Real-World Example (Banking)

In SBI-like systems (your domain 😉):

If a customer record is fetched:

  • KYC service reads it
  • Loan service reads it
  • Risk service reads it

Within same request → only one DB hit

Massive performance gain.


Common Mistake Developers Make

Thinking:

“Hibernate cache is not working”

Reality:

New request = New EntityManager = New cache

So cache was working perfectly.


Bonus Trick (Performance)

Use:

@PersistenceContext
EntityManager em;

Instead of manually creating:

emf.createEntityManager();

Spring then manages lifecycle and caching optimally.


Final Mental Model

HTTP Request
   ↓
EntityManager created
   ↓
Persistence Context (Cache)
   ↓
Multiple find() → One DB hit
   ↓
Request ends → Cache destroyed

 

Leave a Reply