Sub topic 15
When caching helps and when it hides problems
This chapter assumes you know the persistence context, lazy loading, and the fixes for N+1 from earlier chapters (JOIN FETCH, @EntityGraph, batch fetching, DTO projections). It also assumes you can read Hibernate statistics. Caching is the last tool to reach for, not the first.
The caches Hibernate already has
Hibernate has three cache levels. Only the first is on by default.
| Cache | Scope | Default | What it stores |
|---|---|---|---|
| First-level (persistence context) | One session or transaction | Always on | Entities loaded or saved in this unit of work |
| Second-level | Whole `SessionFactory`, shared by all sessions | Off | Entity and collection state, keyed by id |
| Query cache | Whole `SessionFactory` | Off | Lists of ids returned by a specific query and its parameters |
The first-level cache is why findById called twice in one transaction runs one SQL statement. It does not help across requests, and it does nothing for a lazy collection that has not been loaded yet.
Why a cache can hide N+1
Suppose authorSummaries() still has the N+1 pattern, but Author and Book are in the second-level cache. After a warm-up, every lazy load is a cache hit. The SQL log looks clean, and the statement count in a test can drop to near zero.
The code is still wrong. Each lazy load still goes through Hibernate, builds entities from cached state, and costs CPU and memory. The problem returns on a cold start, after a cache eviction, or after a write invalidates the cached collection. A fix such as JOIN FETCH removes the problem at the source, and the cache then only adds speed on top.
Turning on the second-level cache
The second-level cache needs a JCache provider such as Ehcache. These properties enable it. They assume the provider is on the classpath.
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=jcache
spring.jpa.properties.hibernate.javax.cache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=createThen mark each cacheable entity and collection explicitly:
import jakarta.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country {
@Id
private Long id;
private String name;
protected Country() {}
public Long getId() { return id; }
public String getName() { return name; }
}READ_WRITE keeps the cache consistent with writes made through Hibernate. READ_ONLY is faster and fits data that never changes.
When caching helps
- Reference data. Countries, currencies, and status codes are read often and change rarely.
- Read-heavy entities loaded by id. A cache hit avoids a round trip to the database.
- Data you own. Writes must go through Hibernate, so it can invalidate entries.
When caching hurts
- Frequently updated data. Each write invalidates cache entries, so you pay for the cache and rarely get a hit.
- Direct SQL updates. A native update or another application changing the table leaves stale entries.
- Multiple application instances. Without a distributed or clustered provider, each node has its own cache, and they can disagree.
- Query results. The query cache is invalidated whenever any table in the query is written, so it only works for tables that are almost static.
A safe order of work
- Measure statements with SQL logging and statistics.
- Fix N+1 at the query level with a fetch strategy or a projection.
- Cache only data that is read often and changes rarely.
- Re-measure with the cache disabled, so you can see the real query count.
Exercise
After enabling the second-level cache, your SQL log shows far fewer statements for authorSummaries(), which still loads each author's books lazily. Is the N+1 problem fixed? Why or why not?
Show answer
No. The lazy loads still happen, and they are only answered from the cache. The queries come back on a cold start, after eviction, or after a write invalidates the cached collection. Fix it with JOIN FETCH, @EntityGraph, batch fetching, or a DTO projection, and then test with the cache disabled.