JPA L1 Caching
First-level (persistence context) cache — how Hibernate avoids duplicate DB hits within a session
- Explain how the persistence context acts as an L1 cache
- Demonstrate repeated entity.find() returning cached instance
- Clear the context with EntityManager.clear() to force a re-read
EntityManager. A brief recap of the lifecycle is included below to keep these notes self-contained.Overview
First Level Caching is a built-in, automatic caching mechanism provided by JPA (Java Persistence API) through the Persistence Context. It operates at the EntityManager level and ensures that within a single unit of work (a single EntityManager instance), the same database row is never fetched more than once — even if you call find() multiple times for the same primary key.
This cache is called "first level" because it is the most immediate, closest layer of caching between your application code and the database. It is always active and cannot be disabled.
Why This Concept Exists
Problem It Solves
Without any caching, every call to find() or a query method would result in a SQL SELECT statement going to the database. In a single HTTP request that retrieves the same entity multiple times (for example, in a service that loads a user and then passes it to multiple validators), this would cause redundant database round-trips, increasing latency and load on the database.
Purpose
- Reduce unnecessary database queries within a single unit of work.
- Maintain a consistent view of entity state within a transaction — if you modify an object and then read it again, you should see your modification, not the old database value.
- Support the JPA lifecycle model where entities transition through states (
NEW → MANAGED → REMOVED → DETACHED) without every state change immediately hitting the database.
Prerequisites: JPA Lifecycle Recap
Before understanding first level caching, you must understand the JPA entity lifecycle.
Entity States
| State | Description |
|---|---|
| New (Transient) | Object created with new, not associated with any EntityManager or persistence context. Not tracked. |
| Managed (Persistent) | Associated with a persistence context. Changes are tracked and will be synced to DB on flush/commit. |
| Removed | Scheduled for deletion. Still inside persistence context but marked for removal. Will be deleted on flush/commit. |
| Detached | Was managed, but the EntityManager was closed or detach() was called. Changes are no longer tracked. |
Lifecycle Diagram
Key Lifecycle Rule
Lifecycle Example (from the lecture)
1UserEntity a = new UserEntity(); // State: NEW2
3entityManager.getTransaction().begin();4
5entityManager.persist(a); // State: MANAGED — stored in Persistence Context, NOT yet in DB6
7entityManager.remove(a); // State: REMOVED — marked for deletion, still in Persistence Context8
9entityManager.persist(a); // State: MANAGED again — removal cancelled10
11entityManager.getTransaction().commit(); // FLUSH happens: INSERT query fires, data goes to DBWhat actually happens at the DB level: Only one INSERT query fires at commit time. All the intermediate state changes (persist → remove → persist) happen in the persistence context in memory — no SQL is generated for each individual call.
Definition
First Level Cache
is the cache associated with the EntityManager (or Hibernate Session). It is scoped to the lifetime of a single EntityManager instance. Within that scope, every entity loaded or persisted is stored in the Persistence Context, which acts as an identity map. Subsequent lookups for the same entity by primary key are served from this in-memory map without hitting the database.
Real-World Analogy
Think of the Persistence Context as a shopping cart in a store session.
- You walk into the store (start an HTTP request → EntityManager is created).
- You pick up items (persist entities).
- You look at items you already picked up (find by ID) — you don't go back to the shelf; they're already in your cart.
- You check out (commit/flush) — the final state of your cart goes to the cashier (database).
- When you leave and someone else walks in (new HTTP request → new EntityManager), they start with a completely empty cart. They have no knowledge of what was in yours.
Core Concepts
Persistence Context
The Persistence Context is the in-memory workspace managed by the EntityManager. It:
- Stores all entities that have been loaded or persisted during the current
EntityManagerlifetime. - Tracks the state of each entity (Managed, Removed, etc.).
- Acts as a first-level cache — the same entity (by primary key) is never fetched from the DB twice within the same persistence context.
- Is implemented internally as a Map (identity map) where the key is derived from the entity's primary key and type, and the value is the entity object.
EntityManager Persistence Context Relationship
1One EntityManager = One Persistence Context- If you create two
EntityManagerinstances, each has its own separate persistence context. - These two persistence contexts are completely isolated — data visible in one is invisible to the other.
- This is the fundamental reason why first-level caching is scoped to a single EntityManager.
EntityManager Lifecycle in Spring / Dispatcher Servlet
In a Spring MVC application:
DispatcherServletis the front controller — every HTTP request passes through it.- Before invoking the controller,
DispatcherServletruns pre-handle interceptors. - One of these interceptors creates an
EntityManagerFactory(created once at application startup) and from it creates a newEntityManagerfor this HTTP request. - Every HTTP request gets exactly one
EntityManager. - All JPA/Spring Data JPA operations within that HTTP request (whether
save(),findById(), custom queries) use the sameEntityManagerand therefore the same persistence context. - When the HTTP request ends, the
EntityManageris closed, and the persistence context is destroyed.
Internal Working
How the Persistence Context Cache Works (Internally)
Internally, Hibernate's SessionImpl (which implements JPA's EntityManager) maintains the persistence context as a StatefulPersistenceContext. This class holds a Map where:
- Key: A composite of the entity type + primary key value.
- Value: The actual entity object.
When you call entityManager.persist(entity):
- Hibernate checks if the entity is already in the map (
putIfAbsentsemantics). - If not, it adds the entity to the map.
- The entity is now in MANAGED state.
- No SQL is fired yet.
When you call entityManager.find(UserEntity.class, 1L):
- Hibernate first checks the persistence context map for the key
(UserEntity, 1L). - If found → returns the cached object. No SELECT query.
- If not found → fires a
SELECTSQL query to the database, loads the entity, stores it in the map, and returns it.
Syntax
Using Spring Data JPA (Most Common)
1// Repository interface2public interface UserDetailRepository extends JpaRepository<UserEntity, Long> {3 // No custom code needed for basic CRUD4}5
6// Service7@Service8public class UserDetailService {9
10 @Autowired11 private UserDetailRepository userDetailRepository;12
13 @Transactional14 public UserEntity saveUser(UserEntity user) {15 return userDetailRepository.save(user); // internally calls entityManager.persist()16 }17
18 public Optional<UserEntity> getUser(Long id) {19 return userDetailRepository.findById(id); // internally calls entityManager.find()20 }21}Using EntityManager Directly (Manual / Verbose)
1@Autowired2private EntityManagerFactory entityManagerFactory;3
4public void demonstrateFirstLevelCache() {5 EntityManager em = entityManagerFactory.createEntityManager();6 em.getTransaction().begin();7
8 UserEntity user = new UserEntity();9 user.setName("Alice");10
11 em.persist(user); // Entity stored in Persistence Context. No INSERT yet.12
13 UserEntity found1 = em.find(UserEntity.class, user.getId()); // Cache HIT — no SELECT14 UserEntity found2 = em.find(UserEntity.class, user.getId()); // Cache HIT — no SELECT15
16 System.out.println(found1 == found2); // true — same object reference from cache17
18 em.getTransaction().commit(); // FLUSH: INSERT SQL fires now19 em.close(); // Persistence Context destroyed20}Code Examples
Example 1 Basic First Level Cache: Same HTTP Request
Scenario: Save a user, then immediately fetch the same user within the same HTTP request.
Controller:
1@RestController2public class EntityController {3
4 @Autowired5 private UserDetailService userDetailService;6
7 @GetMapping("/test-jpa")8 public UserEntity testJpa() {9 UserEntity user = new UserEntity();10 user.setName("Alice");11
12 userDetailService.saveUser(user); // INSERT fires on commit13 return userDetailService.getUser(user.getId()); // NO SELECT — served from cache14 }15}Service:
1@Service2public class UserDetailService {3
4 @Autowired5 private UserDetailRepository userDetailRepository;6
7 @Transactional8 public UserEntity saveUser(UserEntity user) {9 return userDetailRepository.save(user);10 }11
12 public Optional<UserEntity> getUser(Long id) {13 return userDetailRepository.findById(id);14 }15}Expected Console Output:
1Hibernate: insert into user_entity (name) values (?)getUser() was called. The data was returned from the first-level cache (persistence context), not from the database.Why no SELECT?
saveUser()is@Transactional, so Spring creates anEntityManagerfor it, callspersist(), and commits (flushing to DB).getUser()runs in the same HTTP request, so Spring detects there is already an activeEntityManager(or the sameEntityManagerFactorycontext is reused for this request scope) and the persistence context already hasuserin it.findById()internally callsem.find()→ checks persistence context → cache hit → no DB round-trip.
Example 2 New HTTP Request, New EntityManager
Scenario: A second API endpoint fetches the same user twice. Since this is a new HTTP request, a new EntityManager is created with an empty persistence context.
Controller:
1@GetMapping("/read-jpa")2public List<UserEntity> readJpa() {3 Long id = 1L;4 UserEntity first = userDetailService.getUser(id); // SELECT fires — cache miss5 UserEntity second = userDetailService.getUser(id); // No SELECT — cache hit6 return List.of(first, second);7}Expected Console Output:
1Hibernate: select u.* from user_entity u where u.id=?getUser() is called twice. The first call misses the cache (empty persistence context) and fires a SELECT. The entity is then stored in the persistence context. The second call hits the cache.Example 3 Manual EntityManager: Full Demonstration
1@Autowired2private EntityManagerFactory entityManagerFactory;3
4public void runDemo() {5
6 // === First EntityManager ===7 EntityManager em1 = entityManagerFactory.createEntityManager();8 em1.getTransaction().begin();9
10 UserEntity user = new UserEntity();11 user.setName("Bob");12
13 em1.persist(user); // Stored in PC1. No INSERT yet.14
15 // Same EM — both hits are cache hits. No SELECT queries.16 UserEntity r1 = em1.find(UserEntity.class, user.getId()); // Cache HIT17 UserEntity r2 = em1.find(UserEntity.class, user.getId()); // Cache HIT18
19 System.out.println("r1 == r2: " + (r1 == r2)); // true20
21 em1.getTransaction().commit(); // FLUSH → INSERT fires now22 em1.close(); // PC1 destroyed23
24 // === Second EntityManager ===25 EntityManager em2 = entityManagerFactory.createEntityManager();26 em2.getTransaction().begin();27
28 // em2 has a fresh persistence context — no knowledge of em1's data29 UserEntity s1 = em2.find(UserEntity.class, user.getId()); // Cache MISS → SELECT fires30 UserEntity s2 = em2.find(UserEntity.class, user.getId()); // Cache HIT — no SELECT31
32 System.out.println("s1 == s2: " + (s1 == s2)); // true33
34 em2.getTransaction().commit();35 em2.close();36}Expected Console Output:
1Hibernate: insert into user_entity (name, id) values (?, ?)2Hibernate: select u.* from user_entity u where u.id=?Line-by-Line Explanation:
| Line | What Happens |
|---|---|
em1.persist(user) | Entity stored in PC1 (in-memory map). No DB interaction. |
em1.find(...) x2 | Both look up the map. Key found both times. No SQL fired. |
em1.commit() | Flush happens. INSERT SQL is generated and sent to DB. |
em1.close() | PC1 is destroyed. Entity state is lost from memory. |
em2.find(...) (1st) | PC2 is empty. Cache miss. SELECT fires. Entity loaded from DB and stored in PC2. |
em2.find(...) (2nd) | PC2 now has the entity. Cache hit. No SQL. |
em2.commit() | Nothing to flush (no modifications). |
em2.close() | PC2 destroyed. |
Step-by-Step Execution Flow
Memory Representation
During a Single HTTP Request
1┌─────────────────────────────────────────────────────┐2│ JVM Memory │3│ │4│ ┌─────────────────────────────────────────────┐ │5│ │ EntityManager (em1) │ │6│ │ │ │7│ │ ┌───────────────────────────────────────┐ │ │8│ │ │ Persistence Context (PC1) │ │ │9│ │ │ (StatefulPersistenceContext) │ │ │10│ │ │ │ │ │11│ │ │ Map { │ │ │12│ │ │ (UserEntity, 1L) → UserEntity@123 │ │ │13│ │ │ (UserEntity, 2L) → UserEntity@456 │ │ │14│ │ │ } │ │ │15│ │ └───────────────────────────────────────┘ │ │16│ └─────────────────────────────────────────────┘ │17│ │18│ Heap: UserEntity@123 { id=1, name="Alice" } │19│ Heap: UserEntity@456 { id=2, name="Bob" } │20└─────────────────────────────────────────────────────┘21 │22 (flush/commit)23 │24 ▼25┌─────────────────────────────────────────────────────┐26│ Database │27│ user_entity: | id | name | │28│ | 1 | Alice | │29│ | 2 | Bob | │30└─────────────────────────────────────────────────────┘Stack
- Each method call (
persist,find, etc.) creates a stack frame. - The
EntityManagerreference is held in the service/repository layer.
Heap
- Entity objects (
UserEntity) live on the heap. - The persistence context
Mapalso lives on the heap, holding references to these objects. - The entity object in the cache and the entity object you hold a reference to are the same object in memory (same reference).
Key Observations
- First-level cache is always on. You cannot disable it. It is a core part of JPA and Hibernate.
- Scope = One EntityManager. When the
EntityManageris closed, the cache is gone.
- In Spring MVC: Scope = One HTTP Request.
DispatcherServletcreates oneEntityManagerper HTTP request.
persist()stores in cache before DB. The entity is in the cache even before the INSERT hits the database.
find()checks cache first. If the entity is already in the persistence context (managed), no SQL is generated.
- Identity guarantee. Within the same persistence context, calling
find()twice for the same ID returns the same Java object (same reference,==returnstrue).
- Two EntityManagers are fully isolated. There is no sharing of cache state between two
EntityManagerinstances, even if they are connected to the same database and running in the same JVM.
- This is NOT second-level caching. Second-level caching is shared across EntityManagers and requires explicit configuration (e.g., Ehcache, Infinispan). First-level caching is automatic and per-EntityManager.
Common Mistakes
Mistake 1 Expecting Second Request to Use Same Cache
1// Request 1: saves user2@GetMapping("/save")3public void save() {4 userService.saveUser(new UserEntity("Alice"));5}6
7// Request 2: expects cache hit — WRONG assumption8@GetMapping("/get")9public UserEntity get() {10 return userService.getUser(1L); // This WILL fire a SELECT — new EntityManager, new cache11}EntityManager with an empty persistence context. First-level cache does not survive across HTTP requests. If you need cross-request caching, you need second-level caching.Mistake 2 Thinking DB Is Queried on Every `persist()`
1em.persist(user1); // Beginner thinks: "INSERT fires now"2em.persist(user2); // Beginner thinks: "INSERT fires now"3em.getTransaction().commit(); // Reality: BOTH inserts fire herepersist() only moves the entity to the persistence context (Managed state). The actual INSERT only happens during flush, which by default happens at commit. This is called write-behind or transactional write-behind.Mistake 3 Assuming `findById()` Always Hits DB
1// Both lines below are in the same transaction / same EntityManager scope2Optional<UserEntity> u1 = repo.findById(1L); // SELECT fires3Optional<UserEntity> u2 = repo.findById(1L); // NO SELECT — cache hitMany developers are surprised that the second call generates no SQL. This is correct and expected behavior. Use this to your advantage.
Mistake 4 Using Multiple EntityManagers and Wondering Why Cache Doesn't Work
1EntityManager em1 = factory.createEntityManager();2em1.persist(user);3em1.getTransaction().commit();4
5EntityManager em2 = factory.createEntityManager();6UserEntity found = em2.find(UserEntity.class, 1L); // Will fire SELECT — em2 has empty cacheEntityManager is its own isolated unit. em2 knows nothing about em1's persistence context.Best Practices
- Let Spring manage EntityManagers. Use
@Transactionaland Spring Data JPA repositories. Don't createEntityManagerinstances manually unless you have a specific reason (testing, custom batch operations).
- Batch operations within one transaction. If you need to load and process multiple entities, do it within a single transaction / EntityManager scope to maximize cache hits and minimize DB round-trips.
- Understand transaction boundaries. Know where your
@Transactionalannotations begin and end. Cache is only effective within one persistence context scope.
- Don't fight the cache. If you explicitly need fresh data from DB within the same transaction, use
em.refresh(entity)— but understand that this adds a SELECT query.
- For cross-request caching, use second-level cache. Configure Ehcache or similar. Don't try to manually work around first-level cache for cross-request sharing.
Interview Notes
Common Interview Questions
Q: What is first-level caching in JPA/Hibernate?
A: First-level cache is the cache maintained by the EntityManager (Hibernate Session) within the scope of a single persistence context. It stores all managed entities in a Map keyed by entity type and primary key. Any find() call for an entity already in the persistence context returns the cached object without hitting the database.
Q: Can first-level cache be disabled?
A: No. It is always enabled and is a fundamental part of JPA / Hibernate. It cannot be disabled.
Q: What is the scope of first-level cache?
A: It is scoped to the lifetime of a single EntityManager (or Hibernate Session). In Spring MVC, this typically means one HTTP request.
Q: What is the difference between first-level and second-level cache?
| First-Level Cache | Second-Level Cache | |
|---|---|---|
| Scope | Single EntityManager | Shared across EntityManagers |
| Always active? | Yes | No — must be explicitly enabled |
| Implementation | Built into JPA / Hibernate | External (Ehcache, Infinispan, etc.) |
| Survives HTTP request? | No | Yes |
| Configuration needed? | None | Yes |
Q: If you call findById(1L) three times in the same request, how many SELECT queries fire?
A: At most one. The first call may fire a SELECT (if the entity isn't already in the context). Subsequent calls are served from the cache.
Q: What happens if you persist an entity and then find it by ID within the same EntityManager before commit?
A: The find() returns the entity from the persistence context cache without firing a SELECT query, even though the entity is not yet in the database (INSERT hasn't fired yet, as it's before commit).
Q: Is the object returned by two find() calls for the same ID the same Java object?
A: Yes. Within the same persistence context, JPA guarantees identity — the same entity object reference is returned every time.
Q: What happens to the first-level cache when the EntityManager is closed?
A: The persistence context (and the cache) is destroyed. All entities become detached.
Related Concepts
| Concept | Relationship |
|---|---|
| Persistence Context | The mechanism that implements first-level caching |
| EntityManager | One EntityManager = one persistence context = one first-level cache |
| Hibernate Session | Hibernate's implementation of EntityManager; SessionImpl holds StatefulPersistenceContext |
| @Transactional | Defines transaction boundaries; flush/commit triggers DB sync |
| Second-Level Cache | Cross-EntityManager cache; requires explicit configuration |
| Flush | The action of syncing persistence context state to DB |
| Detached State | When an entity leaves the persistence context (cache no longer tracks it) |
| EntityManagerFactory | Factory for creating EntityManagers; created once at app startup |
| DispatcherServlet | In Spring MVC, responsible for creating one EntityManager per HTTP request |
Mind Map
Practice Questions
Easy
- What is the first-level cache in JPA?
- Is the first-level cache enabled by default? Can it be disabled?
- How many
EntityManagerinstances are created per HTTP request in a default Spring MVC application? - If you call
entityManager.persist(user)and thenentityManager.find(UserEntity.class, user.getId()), will a SELECT query fire? Why?
Medium
- A Spring service method is annotated with
@Transactional. Inside it,userRepo.findById(1L)is called three times. How many SELECT queries are generated? Why? - You have two separate REST endpoints. Endpoint A saves a user. Endpoint B fetches the user by ID. Does Endpoint B benefit from first-level caching? Explain.
- Explain the relationship between
EntityManagerFactory,EntityManager, and Persistence Context in the context of caching. - What happens to the entities in the persistence context when
entityManager.close()is called?
Hard
- You call
em.persist(user)without committing, then callem.find(UserEntity.class, user.getId()). The SELECT is not fired. But the data is not in the DB yet. Explain step by step how this works internally. - Two concurrent HTTP requests both try to update the same entity (same ID). Describe what happens at the persistence context level and at the database level. Is there any conflict at the first-level cache level?
- Given two
EntityManagerinstancesem1andem2, both open simultaneously,em1modifies an entity and commits. Ifem2now callsfind()for that same entity ID thatem2had already loaded beforeem1's commit, what doesem2see? Explain the cache behavior and the stale read problem.
Summary
- First-level cache = Persistence Context cache. Scoped to one
EntityManager. - Always active. Cannot be disabled.
- In Spring MVC: One
EntityManagerper HTTP request, created byDispatcherServlet. persist()stores the entity in the persistence context. No DB query yet.find()checks the persistence context first. If found → no SELECT. If not found → SELECT fires and result is cached.- Commit/Flush is when SQL (INSERT/UPDATE/DELETE) is actually sent to the database.
- Two EntityManagers are fully isolated. Each has its own persistence context. No sharing.
- Same entity, same EM → same Java object. Identity is guaranteed within one persistence context.
- First-level ≠ Second-level. Second-level cache is cross-EntityManager, requires setup, and is not covered here.
Mastery check
How well can you recall this?
Finished this lesson?