The query cache in Hibernate is an optional, second-level caching mechanism that stores the results of HQL or Criteria queries, so that the same query with the same parameters can return results without re-executing the SQL against the database.
🔹 How it works:
- When query caching is enabled:
1️⃣ You mark a query as cacheable (per-query).
2️⃣ The first time you run the query, Hibernate executes it against the database, stores the result IDs in the query cache, and caches the entities in the second-level cache.
3️⃣ On subsequent identical queries (same HQL and parameters), Hibernate fetches the result directly from the query cache → no SQL sent.
🔹 Example usage:
List<User> users = session.createQuery("FROM User WHERE active = true", User.class)
.setCacheable(true)
.list();
🔹 In this example:
✅ The first call executes the SQL and caches the result.
✅ Later identical calls reuse the cached result list (IDs of matching rows) + second-level cached entities.
🔹 Important points:
- Query cache doesn’t cache entity data itself — it only caches IDs of query results.
- Actual entity data must be in the second-level cache for query cache hits to be fully effective.
- Query cache is best used for read-heavy, rarely changing queries, like reference data, menus, or lookup tables.
🔹 How to enable globally in configuration:
hibernate.cache.use_query_cache=true
🔹 When not to use it:
- For frequently updated data, because invalidating the cache can cause more overhead than benefit.
- For dynamic queries with constantly changing parameters, as they won’t benefit from caching.
✅ Key takeaway:
Hibernate’s query cache stores query results (IDs) so repeated identical queries avoid hitting the database, but requires second-level cache to cache actual entities for full benefit.