Sub topic 15
When caching helps and when it hides problems
Earlier chapters fixed N+1 by changing how queries fetch data. This chapter covers the other common reaction, which is to turn on a cache. A cache is a legitimate tool, but it can hide an N+1 problem without fixing it. This chapter assumes you know the persistence context, lazy loading, JOIN FETCH, and how to read Hibernate statistics.
Three caches, three scopes
Hibernate has more than one cache. They differ in lifetime and in who shares them.
| Cache | Scope | Enabled by default | What it stores |
|---|---|---|---|
| First-level (persistence context) | One `EntityManager`, usually one transaction | Always on | Managed entities, by id |
| Second-level | The whole `SessionFactory`, shared by all transactions | No | Entity state, collection ids, natural-id lookups |
| Query cache | The whole `SessionFactory` | No | Result ids for a query and its parameters |
The first-level cache is why findById twice in one transaction runs one SELECT. It is also why lazy loading works. It disappears when the transaction ends, so it never makes a request faster than the previous one.
The second-level cache lives across transactions. Hibernate checks it before it goes to the database.
Enabling the second-level cache
Hibernate does not ship a cache implementation. It delegates to a provider through JCache (JSR-107). Ehcache 3 is a common choice. Add org.hibernate.orm:hibernate-jcache and the Jakarta build of Ehcache (org.ehcache:ehcache with the jakarta classifier) to your build. Then set the following properties:
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=create
spring.jpa.properties.hibernate.generate_statistics=trueCaching is opt-in per entity. Annotate each cacheable entity with @Cacheable (JPA) and @Cache (Hibernate) to choose a concurrency strategy:
import jakarta.persistence.Cacheable;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import java.util.ArrayList;
import java.util.List;
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<Book> books = new ArrayList<>();
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}The concurrency strategies trade safety for speed:
READ_ONLYis fastest and for data that never changes. Updating such an entity throws an exception.READ_WRITEis the usual choice for data that changes occasionally. It uses soft locks to avoid serving stale data inside a single node.NONSTRICT_READ_WRITEskips locking, so brief staleness is possible after an update.TRANSACTIONALneeds a JTA-aware provider, so it rarely applies to a typical Spring Boot service.
A cached collection stores only the ids of its elements, not the elements themselves. The Book entity must also be annotated with @Cacheable and @Cache. If it is not, a cache hit on author.getBooks() loads each book with its own SELECT, and you have rebuilt N+1 behind a cache.
The query cache
The second-level cache answers lookups by id. A JPQL query that returns a list of authors does not use it unless you also enable the query cache and mark the query as cacheable:
spring.jpa.properties.hibernate.cache.use_query_cache=trueimport jakarta.persistence.QueryHint;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface AuthorLookupRepository extends JpaRepository<Author, Long> {
@QueryHints(@QueryHint(name = "org.hibernate.cacheable", value = "true"))
@Query("select a from Author a where a.name = :name")
List<Author> findByNameCached(@Param("name") String name);
}The query cache stores a list of ids for each query and parameter combination. It then loads the entities through the second-level cache. The query cache has two weaknesses:
- Hibernate keeps a timestamp per table. Any insert, update, or delete on a table invalidates every cached query that touches it. A write-heavy table gets almost no benefit.
- If the entity is not in the second-level cache, each id in a cached result triggers its own
SELECT. This is the same N+1 problem again.
Use the query cache for queries that run often, take stable parameters, and read tables that rarely change.
How a cache hides N+1
Take the authorSummaries() method from earlier chapters. It loads all authors, then touches each getBooks(). With the cache off, the log shows 1 + N statements. Enable caching on both entities and the collection, then call it twice:
- The first call is cold. It runs 1 + N statements and fills the cache.
- The second call is warm. Each collection is served from the cache, and the log is quiet.
The code has not changed. It is still an N+1 pattern, and the cache is the only reason it looks fast. It breaks again in these situations:
- After an application restart, when every cache region is empty.
- After a deployment to a new node, because the default provider keeps its cache in each JVM's memory.
- After a write to
AuthororBook, which evicts the affected entries. - After entries expire or the cache reaches its size limit.
- Under a new access pattern that touches rows that were never cached.
The cold-start path is the one your users meet after every deployment, and it is the slowest path in the system. A load test that runs after a warm-up will not show it.
Measuring cache behavior
Hibernate statistics report cache activity next to statement counts. The relevant counters are getSecondLevelCacheHitCount(), getSecondLevelCacheMissCount(), and getSecondLevelCachePutCount(). A high hit count with a high statement count on a cold start is the signature of a hidden N+1.
For query-count tests, turn the second-level cache off. The test then measures the SQL the code needs, and a later warm cache cannot hide a regression.
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(properties = {
"spring.jpa.properties.hibernate.cache.use_second_level_cache=false",
"spring.jpa.properties.hibernate.cache.use_query_cache=false",
"spring.jpa.properties.hibernate.generate_statistics=true"
})
class AuthorColdQueryCountTest {
@Autowired
EntityManagerFactory entityManagerFactory;
@Autowired
AuthorService authorService;
@Test
void summariesNeedOneStatementWithoutAnyCache() {
Statistics statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
statistics.clear();
authorService.authorSummaries();
assertThat(statistics.getPrepareStatementCount()).isEqualTo(1);
}
}This test assumes you have already applied a fix, such as JOIN FETCH, to authorSummaries(). Before the fix, it fails with 1 + N statements, which is the result you want from a guard.
What belongs in a cache
Caching is a good fit when the data has these properties:
- It is read far more often than it is written, such as countries, currencies, product categories, and feature flags.
- A small amount of staleness is acceptable.
- The set is small enough to fit in memory.
- It is read by id or by a natural key, not through many different queries.
Caching is a poor fit when the data changes often, when correctness depends on the latest row, or when the table is large and accessed unevenly. It is also a poor fit if you run several application nodes and cannot tolerate the default per-node caches disagreeing. A clustered provider fixes that, but it adds operational cost.
A practical order of work:
- Fix the query shape with
JOIN FETCH,@EntityGraph, batch fetching, or a DTO projection. - Add a query-count test with all caches disabled.
- Cache only reference data that measurement shows is hot.
- Watch the hit ratio in production. A cache with a low hit ratio costs memory and invalidation work and gives little back.
Exercise
A team enables the second-level cache on Author and the Author.books collection. Their load test, run after a warm-up, shows authorSummaries() with no SQL after the first call, so they close the N+1 ticket. Give two reasons the ticket should stay open, and one change to the test setup that would expose the problem.
Show answer
First, a cached collection holds only the ids of its books. If Book is not itself cached, each book is still loaded with its own SELECT. Second, the cache is empty after every restart, deployment to a new node, eviction, or write to the affected tables, so the 1 + N statements return on those paths. To expose the problem, run the query-count test with the second-level and query caches disabled, or clear the cache before measuring, and assert on getPrepareStatementCount(). The test fails until the query itself is fixed.