Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Caching and Performance

The Second-Level Cache

Learn how the Hibernate second-level cache works, how to enable it with JCache providers, choose concurrency strategies, and avoid stale data and wasted memory.

The first-level cache lives inside one Session and disappears with it. The second-level cache (L2) belongs to the SessionFactory: it is shared by all sessions of the application, so a row loaded by one request can be served to the next one without touching the database. Used on the right data it removes a large share of read traffic; used on the wrong data it returns stale values and eats memory.

Hibernate and cache providers (Ehcache, Infinispan, Caffeine through JCache) are not available here, so the configuration is read-only. The runnable program builds a small read-through cache with expiry and invalidation to show what the L2 cache does for you.

What gets cached

L2 does not store entity objects. It stores a disassembled form: a map from id to the column values (plus ids of associations). On a hit, Hibernate rebuilds a fresh entity in the current session. Consequences:

  • Two sessions never share the same Java instance, so thread safety is not an issue.
  • Associations are stored as ids; to avoid loading them separately you cache them too.
  • Collections are cached per collection role, as lists of element ids.

Lookups happen in session.find/get/byId, and when a lazy proxy or association is initialized. A normal HQL query does not use L2 for its rows (see Query Cache and Cache Regions), although entities returned by it can be stored in L2 for later id lookups.

Enabling it

PROPERTIES
hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=jcache
hibernate.javax.cache.provider=org.ehcache.jsr107.EhcacheCachingProvider
hibernate.javax.cache.uri=/ehcache.xml
hibernate.cache.default_cache_concurrency_strategy=read-write

Then mark the entities, and the collections, that should be cached:

Java
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "catalog")
public class Product {
    @Id Long id;
    String name;

    @OneToMany(mappedBy = "product")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    List<Review> reviews;
}

hibernate.cache.use_second_level_cache defaults to true in recent versions, but nothing is cached until an entity is annotated (or jakarta.persistence.sharedCache.mode is ALL). Spring Boot users set spring.jpa.properties.hibernate.cache... and add the JCache provider dependency.

Concurrency strategies

Strategy Meaning Use for
READ_ONLY never updated; fastest reference data (countries, currencies)
NONSTRICT_READ_WRITE updates evict entries after commit; small stale window data that rarely changes and tolerates brief staleness
READ_WRITE soft locks keep readers from seeing uncommitted data most mutable data in one JVM or cluster
TRANSACTIONAL full JTA transaction cache rare, needs JTA-aware provider

READ_ONLY throws an exception if you try to update the entity, which is exactly the point: the cache can then skip all invalidation logic.

Invalidation and the cluster problem

When a session updates or deletes a cached entity, Hibernate evicts or updates the entry when the transaction commits. That keeps L2 right as long as every write goes through Hibernate. A trigger, a script, a second application or a native update without declared query spaces changes rows behind the cache's back, and readers keep seeing old data until the entry expires.

In a cluster each node has its own cache unless the provider replicates it (Infinispan, Hazelcast) or invalidates remote copies. If you run several instances with a local-only cache, give regions a short time to live.

Manual control:

Java
Cache cache = sessionFactory.getCache();
cache.evict(Product.class, 42L);          // one entity
cache.evictEntityData(Product.class);      // every Product
cache.evictAllRegions();                   // everything

Per session, session.setCacheMode(CacheMode.IGNORE) (or GET, PUT, REFRESH) controls how a unit of work interacts with the cache, which is useful in bulk imports.

Java A read-through cache with expiry and invalidation (stand-in for L2)

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.

What to cache, and what not to

Good candidates: data that is read very often and changes rarely, is looked up by id, and is the same for every user: currencies, countries, product categories, permissions, configuration rows. Poor candidates: rows that change on every request, huge tables, per-user data, anything where a few seconds of staleness is unacceptable (balances, stock levels).

Always size regions (maximum entries, time to live), enable provider statistics, and watch the hit ratio with Statistics#getSecondLevelCacheHitCount() and ...MissCount(). A cache with a 20% hit ratio costs more than it saves.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the second-level cache store for an entity?

    L2 keeps the loaded state, not the instance, so each session builds its own fresh entity and no thread sharing issues arise.
  2. 2. Which strategy fits a table of country codes that never changes?

    READ_ONLY is the fastest and rejects updates, ideal for immutable reference data.
  3. 3. Why can the L2 cache return stale data?

    Eviction is driven by Hibernate's own writes, so outside changes need a short TTL or manual eviction.
  4. 4. Which call removes every cached Product from L2?

    session.clear() only affects the first-level cache. The Cache API on the SessionFactory controls L2.

Summary

  • L2 is shared per SessionFactory, stores disassembled state and is consulted by id lookups and association loading.
  • Enable a JCache provider, annotate entities with @Cache, and pick the weakest strategy that is correct (READ_ONLY, then READ_WRITE).
  • Writes outside Hibernate and cluster nodes cause stale data; use short TTLs or invalidation.
  • Cache read-heavy, rarely changed data and measure the hit ratio.

Next: Query Cache and Cache Regions