✅ What happens when you load an entity?
When you fetch an entity with Hibernate (e.g., em.find()
or HQL query), the lookup happens in order:
1️⃣ First-level cache (1st-level) — also called the persistence context or session cache:
- Every open
EntityManager
or HibernateSession
has its own first-level cache. - When you load an entity during a session, it’s stored here.
- Repeated accesses to the same entity within the same session return the cached instance without hitting the database or 2nd-level cache.
2️⃣ Second-level cache (2nd-level) — optional, shared across sessions:
- Configured explicitly with a provider (e.g., Ehcache, Infinispan).
- Stores entities between sessions so they can be reused across transactions or requests.
- If an entity isn’t in the first-level cache but is found in the second-level cache, Hibernate loads it from there instead of querying the database.
3️⃣ Database
- If the entity is in neither the first-level nor the second-level cache, Hibernate executes SQL to load it.
🔎 Where will the entity “live”?
- Once loaded, the entity always lives in the first-level cache of the current session until that session ends (or you evict the entity from the session).
- If second-level caching is enabled and properly configured for the entity:
- When you first load the entity from the database, Hibernate will put a copy into the second-level cache.
- Later sessions can check the second-level cache and reuse that entity without querying the DB.
✅ So the answer:
After loading, the active instance of the entity “lives” in the 1st-level cache, and a copy may live in the 2nd-level cache for reuse across sessions.
🔥 Example flow:
- Session 1:
- Load entity with ID=1 → 1st-level cache is empty → 2nd-level cache is checked.
- If not in 2nd-level → DB query → entity added to both 1st-level and 2nd-level cache.
- Still in Session 1:
- Access entity again → served from 1st-level cache.
- Session 2:
- Load entity with ID=1 → 1st-level cache (of Session 2) is empty → 2nd-level cache is checked → if found, loaded into Session 2’s 1st-level cache.
🚨 Key points:
✔ First-level cache is mandatory, always enabled, and tied to the lifecycle of the current session.
✔ Second-level cache is optional, shared across sessions, and must be explicitly configured per entity or query.
✔ Hibernate never skips 1st-level cache; it always checks it before looking at the 2nd-level cache or database.