Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Caching and Performance

Query Cache and Cache Regions

Understand how the Hibernate query cache stores result ids, how timestamps invalidate it, when it helps, and how to size and monitor cache regions.

The second-level cache answers "give me entity 42". It does not answer "give me the ten most popular products". For repeated queries with the same parameters, Hibernate has a separate query cache. It is off by default, and for good reasons: it only pays off in narrow situations. This lesson explains how it works so you can decide.

The real query cache needs Hibernate and a cache provider, so its code is read-only here. The runnable program reproduces the mechanism (result ids keyed by query and parameters, invalidated by a per-table timestamp) with plain Java.

How it works

PROPERTIES
hibernate.cache.use_query_cache=true
Java
List<Product> top = session.createQuery(
        "from Product p where p.category = :c order by p.sales desc", Product.class)
    .setParameter("c", "tools")
    .setMaxResults(10)
    .setCacheable(true)                      // opt in per query
    .setCacheRegion("queries.topProducts")   // optional
    .getResultList();

The query cache stores only ids (or scalar values for projections). The key is the query text plus parameter values, paging, and a few settings. On a hit Hibernate reads the id list from the cache and loads each entity. If the entities are not in L2 as well, that means one SQL query per id, which is slower than running the query again. So: a cacheable query on entities is only useful when those entities are cached in L2.

Invalidation by timestamp

Hibernate keeps an update-timestamps cache: for every table, the time of its last committed change. When a cached result is stored it gets its own timestamp. On a lookup Hibernate compares: if any table the query touched changed after the result was cached, the entry is stale and the query runs again.

The consequence is blunt: any write to any table in the query throws away all cached results for that table. A table updated once per second gives the query cache a lifetime of about one second. It works well for reference data and nearly static lists, and poorly for tables that change constantly.

Native queries need addSynchronizedEntityClass(...) or addSynchronizedQuerySpace(...) so Hibernate knows which tables to watch.

Java A query cache with table timestamps (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Cache regions

A region is a named bucket of cache entries with its own size and expiry. Hibernate uses a few by default:

Region Content
entity class names (com.acme.Product) disassembled entities
com.acme.Product.reviews a collection role
default-query-results-region query cache results
default-update-timestamps-region table timestamps (never expire or evict this one)

Name your own regions with @Cache(region = ...) and setCacheRegion(...) and configure each one in the provider file:

XML
<!-- ehcache.xml -->
<cache alias="catalog">
  <expiry><ttl unit="minutes">30</ttl></expiry>
  <heap unit="entries">5000</heap>
</cache>
<cache alias="default-update-timestamps-region">
  <heap unit="entries">10000</heap>
</cache>

A short TTL on the timestamps region is a bug: if timestamps expire while results remain, stale results could be served. Keep it unlimited.

Separate regions let you give hot, small reference data a long TTL and volatile data a short one, and let you evict one area without wiping the rest: sessionFactory.getCache().evictQueryRegion("queries.topProducts").

When to use it, and alternatives

Use the query cache when all of these hold: the same query and parameters repeat often, the underlying tables change rarely, the result is smaller than a few hundred rows, and entities are in L2. Examples: a list of categories, feature flags, the menu tree.

Prefer other tools when the data is hot: a dedicated application cache (Caffeine, Redis) keyed by what you need, a materialized view or summary table, or an HTTP cache in front. They give you explicit expiry instead of "any write to the table".

Check that it really helps: Statistics#getQueryCacheHitCount(), getQueryCacheMissCount() and getQueryCachePutCount(). A high put count with few hits means the cache is churned by writes.

Java Why one write wipes the cache (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Hibernate query cache store for an entity query?

    Only ids (or scalar values) are cached. The entities themselves must come from L2 or the database.
  2. 2. When is a cached query result discarded?

    The update-timestamps cache compares table timestamps with the time the result was cached.
  3. 3. Why should the update-timestamps region not expire entries?

    If a table timestamp vanishes while a cached result remains, Hibernate loses the evidence that the table changed.
  4. 4. Which query is a good candidate for setCacheable(true)?

    Rarely changing, parameter-light reference lists give the query cache long-lived entries.

Summary

  • The query cache is opt-in per query and stores ids, so cache the entities in L2 too.
  • Any committed write to a table invalidates all cached queries that touch it.
  • Regions give separate sizes and expiry; keep the timestamps region unlimited.
  • Use it for stable reference lists, measure hits and puts, and prefer an application cache for hot data.

Next: Transactions and Isolation Levels