Hibernate First-Level Cache Explained
Fast recall
Quick revision
Core answer
Whether you understand Hibernate's transaction-scoped caching and the identity guarantee it provides
Confusing the first-level cache (always on, per-transaction) with the second-level cache (optional, cross-transaction)
Explain that the first-level cache guarantees == identity within a transaction and prevents duplicate SELECTs
Interview-ready guide
Interview answer
When entityManager.find(User.class, 7L) loads a managed User, another find for User 7 in the same persistence context can return that same object. This identity guarantee is different from a second-level cache, which may be shared across sessions. Spring usually binds an EntityManager to a transaction, so the scopes often line up, but an extended persistence context can live across transactions. Queries can still reach the database even when some result entities are already managed.
Hibernate First-Level Cache Explained
Direct Answer
Hibernate's first-level cache is the persistence context owned by one Session or EntityManager. It is always present and guarantees that one persistence context has one managed Java instance for a given entity identity. Its lifetime follows that Session or EntityManager, which is often transaction-bound in Spring but is not defined as exactly one transaction in every setup.
Code Example
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class CustomerService {
@PersistenceContext
private EntityManager entityManager;
public void demonstrateFirstLevelCache(Long customerId) {
// First load: hits the database, stores in the first-level cache
Customer customer1 = entityManager.find(Customer.class, customerId);
// Second load: returns the cached instance, NO database hit
Customer customer2 = entityManager.find(Customer.class, customerId);
System.out.println(customer1 == customer2); // true — same object
customer1.setName("Updated Name");
System.out.println(customer2.getName()); // "Updated Name" — same object
} // transaction ends -> first-level cache cleared
}
Common Mistakes & Pitfalls
- Confusing it with the second-level cache — first-level is per-transaction and always on; second-level is cross-transaction, optional, and configured separately.
- Expecting cross-request caching — loading a customer in one request won't be cached in another; the cache clears at commit.
- Not clearing in batch jobs — processing 10,000 rows in one transaction without
flush()andclear()bloats the cache into an OutOfMemoryError.
Check your understanding
Answer these without looking back at the article.
- What is Hibernate's second-level cache?
- Can you disable the first-level cache?
- How does the first-level cache affect duplicate entity loads?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.