✅ Is the query cache an example of second-level cache?
Answer:
🔹 The query cache itself is not the same thing as the second-level cache, but it depends on the second-level cache to work effectively.
- The query cache caches query result sets (i.e., lists of entity IDs matching specific HQL/Criteria queries) → it knows what entities matched a query last time.
- The second-level cache stores actual entity data across sessions.
🔹 How they work together:
- When you execute a cacheable query like:
List<User> users = session.createQuery("FROM User WHERE active = true")
.setCacheable(true)
.list();
Hibernate:
1️⃣ Caches the IDs of the result in the query cache (e.g., [1, 5, 7]).
2️⃣ Looks up each ID in the second-level cache → if entities are cached, returns them without hitting the database.
3️⃣ If an entity is not in the second-level cache, Hibernate still has to query the database for it.
🔹 So:
✅ The query cache is built on top of the second-level cache.
✅ It’s part of Hibernate’s overall second-level caching architecture, but specifically dedicated to caching query result sets, not entity data itself.
🔹 Key difference:
- Second-level cache → caches individual entities across sessions.
- Query cache → caches which IDs matched a specific query → needs second-level cache for entities themselves.
✅ Key takeaway:
The query cache is a specialized layer of second-level caching that caches query results (IDs), but it requires second-level cache for actual entity data to avoid database hits entirely.