Skip to content
javahacks.dev
Hibernate

Hibernate Second Level Cache Guide With Spring Boot

A complete guide to the Hibernate second level cache: JCache setup, entity, collection and query caches, strategies, invalidation, clustering and measuring.

27 min read
Summarize in AI
Flat illustration of an entity class mapped to a database table, with the Hibernate, Spring Boot, OpenJDK and MariaDB logos.

A busy service asks the database the same small questions thousands of times an hour. Which country has code VN? What is the name of category 12? Which currency does this tenant use? Each answer is a row that changes once a month, fetched once per request, by every request, through a connection that other work is waiting for. Hibernate has a feature built for exactly this, the second level cache, and it is also one of the easiest ways to introduce a stale data bug that survives code review. This guide covers the cache from the inside out: what it stores and how, how to switch it on, how each of the four cache types works, the consistency rules, how to configure expiry, what happens across several application nodes and how to know whether it is helping. Every step has working code. The cache sits on top of the session behaviour in Hibernate's first level cache and flush modes, so read that first if the persistence context is unfamiliar.

The one sentence to remember: the second level cache is a copy of rows kept in your JVM, and every question about it is a question about when that copy stops matching the database.

The two levels

Every Hibernate Session has a first level cache, the persistence context. It is automatic, scoped to one session, usually one transaction, and it guarantees that loading the same id twice inside the session returns the same object. It disappears when the session closes.

The second level cache is the opposite in every respect: it is opt in, scoped to the SessionFactory, so shared by every session and every request, and it survives across transactions. It stores the state of an entity, not the entity object, so each session still builds its own instance from the cached data.

First levelSecond level
ScopeOne sessionThe whole SessionFactory
EnabledAlwaysOnly when configured, per entity
LifetimeUntil the session closesUntil evicted or expired
StoresManaged entity instancesDisassembled entity state
Consistency riskNone inside the sessionStale data across sessions and nodes
ProviderHibernate itselfA cache implementation through JCache

The order of lookups on entityManager.find(Country.class, 1L) is: the persistence context first, then the second level cache if the entity is cacheable, then the database. A hit at either level means no SQL.

What gets cached, and what does not

Four kinds of data can live in the second level cache, each in its own region:

  1. Entity data. The column values of an entity, keyed by its id. Hit by find, getReference initialisation and loading a to-one association.
  2. Collection data. For a mapped collection, only the ids of the elements, keyed by owner id. The elements themselves must be cached as entities for the collection cache to avoid SQL.
  3. Natural id mappings. A map from a business key such as code to the primary key, so a lookup by natural id avoids a query.
  4. Query results. The list of ids that a particular query with particular parameters returned, plus a timestamp. This is the query cache, separate from the others and off by default.

What it does not do is just as important. A JPQL query such as from Product p where p.price > 10 is not served from the entity cache. The query goes to the database; the entity cache helps only when Hibernate then needs to load an entity by id. This surprises people who mark an entity cacheable and expect every query to speed up. Only lookups by identifier benefit, unless you also enable the query cache.

The life of a cache entry

It helps to see what actually sits in the cache, because several surprises follow from it. When Hibernate loads a Product row, it does not store the Product object. It disassembles the entity into an array of values in the order of the mapped properties, with associations reduced to their ids, and stores that array under a key made of the entity name, the id and the tenant. A later hit assembles a new Product from the array. That has three consequences. Each session gets its own instance, so the cache can never hand two threads the same mutable object. Associations in a cached entity are ids and are resolved lazily or eagerly as usual, which is why a cache hit on Product does not mean origin is loaded. And a cached entry is a snapshot: nothing keeps it synchronised except Hibernate's own invalidation.

The sequence for a cold read is: look in the persistence context, miss; look in the second level cache, miss; run the SELECT; put the disassembled state into the cache; return the entity. The sequence for a warm read in a new session is: persistence context miss; cache hit; assemble; return. For a write under READ_WRITE there are more steps, covered next.

Concurrency strategies

Marking an entity cacheable requires choosing a concurrency strategy, which defines the consistency guarantee:

StrategyWrites allowedGuaranteeCost
READ_ONLYNoEntry never changesLowest; an update throws
NONSTRICT_READ_WRITEYesEventual: entry evicted after commit, brief stale windowLow
READ_WRITEYesNo stale reads of committed data, using soft locksMedium
TRANSACTIONALYesParticipates in a JTA transactionNeeds a transactional cache provider

READ_ONLY is for reference data you never change through the application: countries, currencies, a fixed list of roles. It is the fastest and the safest, since the cache never needs to be reconciled with a write. READ_WRITE is the default choice for data that does change: when a transaction updates the entity, Hibernate places a soft lock on the cache entry, so other transactions bypass the cache and read from the database until the update commits, after which the entry is replaced. NONSTRICT_READ_WRITE skips the soft lock and evicts the entry after the transaction, accepting that another session may read the old value in the short window between commit and eviction. Use it only when a brief stale read is harmless. TRANSACTIONAL needs a JTA setup and a provider that supports it, which excludes the common JCache providers, so most Spring Boot applications never use it.

The READ_WRITE strategy in motion

The strategies are easiest to understand as a timeline. Two transactions, T1 updating a product's name and T2 reading the same product while T1 is still open, under READ_WRITE:

  1. T1 loads the product (from the cache or the database) and calls setName.
  2. T1 flushes. Hibernate runs the UPDATE and soft locks the cache entry: it replaces the cached state with a lock marker carrying a timestamp.
  3. T2 asks for the product, finds the lock marker, treats it as a miss and reads the database. Under READ COMMITTED the database still shows the old name, because T1 has not committed. T2 does not write to the cache while the entry is locked.
  4. T1 commits. After the commit, Hibernate releases the lock and stores the new state in the cache.
  5. A later read from T3 hits the cache and sees the new name.

The soft lock is why READ_WRITE never serves a stale value that has been replaced by a committed write, and the price is that during a write, readers go to the database. If the transaction rolls back at step 4, the lock is released and the old state is not restored from the lock but evicted, so the next read repopulates it.

A test makes the behaviour concrete, using two threads. The structure is the barrier test from losing updates in JPA: T1 updates and waits before committing, T2 reads and asserts it saw the old value from the database and not a half applied state.

java
@Test
void readerDuringAnUncommittedWriteSeesTheOldCommittedValue() throws Exception {
    var updated = new CountDownLatch(1);
    var mayCommit = new CountDownLatch(1);
    var tx = new TransactionTemplate(tm);

    var writer = CompletableFuture.runAsync(() -> tx.executeWithoutResult(s -> {
        Product p = products.findById(id).orElseThrow();
        p.rename("New name");
        products.flush();                    // UPDATE sent, soft lock placed
        updated.countDown();
        await(mayCommit);
    }));

    updated.await();
    String seen = loadNameInNewSession(id);  // reader must not see "New name" yet
    mayCommit.countDown();
    writer.join();

    assertThat(seen).isEqualTo("Old name");
    assertThat(loadNameInNewSession(id)).isEqualTo("New name");
}

Sizing a region

A heap limit on entries is a guess until you do the arithmetic. Suppose Product has 40,000 rows and you cache 20,000 entries. The question is how much memory that is and whether it covers the traffic. Estimate the size of one disassembled entry: an id, a name of about 40 characters (roughly 100 bytes as a Java string with its header), a few numbers and ids, plus the cache provider's per entry overhead of around 100 to 200 bytes. Call it 400 bytes. Twenty thousand entries is then about 8 MB, which is nothing on a service with a gigabyte of heap.

The second question is coverage. If requests follow a typical skewed pattern in which a small fraction of products draws most of the reads, a cache holding half the rows can still deliver a high hit ratio. If the access pattern is uniform, a cache holding half the rows gives about half hits. Only the statistics from a real workload answer this, which is why measurement belongs before the decision. Start generous, since 8 MB is cheap, watch the eviction counts in the provider's statistics, and shrink only if memory is genuinely tight. For entities with big columns, use a size limit in bytes: Ehcache 3 supports <heap unit="MB">64</heap>, which sizes the tier by memory rather than count, at the cost of the provider measuring object graphs.

Using Caffeine as the provider

If Caffeine is already your local cache, its JCache module avoids a second library. The configuration is a different file but the same idea, and the provider class changes:

src/main/resources/application.yamlYAML
spring:
  jpa:
    properties:
      hibernate:
        cache:
          use_second_level_cache: true
          region.factory_class: jcache
        javax.cache:
          provider: com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider
          uri: classpath:caffeine.conf
src/main/resources/caffeine.confText
caffeine.jcache {
  default {
    policy.maximum.size = 10000
    policy.eager-expiration.after-write = 30m
    monitoring.statistics = true
  }
  "dev.javahacks.catalog.Country" {
    policy.maximum.size = 300
  }
  "default-update-timestamps-region" {
    policy.maximum.size = 5000
  }
}

The file is in HOCON format, a superset of JSON. The default block applies to any region without its own entry, a convenience that Ehcache's XML does not offer. Caffeine evicts with the Window TinyLFU policy and is a good performer, but it has no off heap or disk tier; if you need those, Ehcache is the provider.

Step 1: add a provider

Hibernate does not ship a cache; it defines an SPI and the hibernate-jcache module adapts any JCache (JSR 107) implementation to it. Two providers are common. Ehcache 3 is the long standing one, and Caffeine's JCache module is the choice if you already use Caffeine elsewhere. Add the adapter and one provider:

pom.xmlXML
<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-jcache</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <classifier>jakarta</classifier>
</dependency>

The jakarta classifier matters on Ehcache 3: the default artifact references javax.xml.bind, which breaks on current runtimes. Spring Boot manages the Hibernate version, so hibernate-jcache needs no version number. For Caffeine, depend on com.github.ben-manes.caffeine:jcache instead and set the provider class accordingly in the next step.

Then switch the cache on:

src/main/resources/application.yamlYAML
spring:
  jpa:
    properties:
      jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE
      hibernate:
        cache:
          use_second_level_cache: true
          use_query_cache: false
          region.factory_class: jcache
        javax.cache:
          provider: org.ehcache.jsr107.EhcacheCachingProvider
          uri: classpath:ehcache.xml
        generate_statistics: true

ENABLE_SELECTIVE means only entities annotated as cacheable are stored, the safe default; the alternative, ALL, caches every entity and almost always caches things you did not mean to. generate_statistics is on here because the later sections rely on it, and it should be considered a development and staging setting, since statistics add a little overhead.

Step 2: mark an entity

Two annotations do the work: @Cacheable from Jakarta Persistence, saying the entity is eligible, and @Cache from Hibernate, choosing the strategy. A stable reference entity:

src/main/java/dev/javahacks/catalog/Country.javajava
package dev.javahacks.catalog;

import jakarta.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@NaturalIdCache
public class Country {
    @Id
    private Long id;

    @NaturalId
    @Column(nullable = false, length = 2, updatable = false)
    private String code;

    @Column(nullable = false)
    private String name;

    protected Country() {}

    public Country(Long id, String code, String name) {
        this.id = id;
        this.code = code;
        this.name = name;
    }

    public Long getId() { return id; }
    public String getCode() { return code; }
    public String getName() { return name; }
}

And a regional entity that does change, with a to-one association that will be resolved from the cache:

src/main/java/dev/javahacks/catalog/Product.javajava
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Country origin;

    @ElementCollection
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private Set<String> tags = new HashSet<>();

    // constructors and accessors omitted
}

The @Cache on tags caches the collection, which, as noted above, stores only the element values for a basic collection; for an association between entities it stores ids. Without that second annotation the collection is loaded from the database every time, even when its owner is cached.

Step 3: configure regions

Each cached entity gets a region named after its fully qualified class. Without configuration, the JCache provider applies a default, and for Ehcache 3 that can mean entries that never expire, which is the setting you least want on READ_WRITE data. Give every region a size and a time to live in ehcache.xml:

src/main/resources/ehcache.xmlXML
<config xmlns="http://www.ehcache.org/v3"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107">

    <service>
        <jsr107:defaults enable-statistics="true"/>
    </service>

    <cache alias="dev.javahacks.catalog.Country">
        <expiry><none/></expiry>
        <heap unit="entries">300</heap>
    </cache>

    <cache alias="dev.javahacks.catalog.Product">
        <expiry><ttl unit="minutes">30</ttl></expiry>
        <heap unit="entries">20000</heap>
    </cache>

    <cache alias="dev.javahacks.catalog.Product.tags">
        <expiry><ttl unit="minutes">30</ttl></expiry>
        <heap unit="entries">20000</heap>
    </cache>

    <cache alias="default-update-timestamps-region">
        <expiry><none/></expiry>
        <heap unit="entries">5000</heap>
    </cache>

    <cache alias="default-query-results-region">
        <expiry><ttl unit="minutes">10</ttl></expiry>
        <heap unit="entries">1000</heap>
    </cache>
</config>

Read the choices. Country never expires because it is read only and tiny: there are fewer than 300 countries. Product expires after thirty minutes, a safety net so that a missed invalidation heals itself, and holds at most twenty thousand entries so the heap use is bounded. The two default- regions are Hibernate's own and must exist if you use the query cache: the update timestamps region must never evict entries, or the query cache would serve results it should have invalidated. If Hibernate cannot find a region configured, Ehcache creates one with defaults and logs a warning, so scan the startup log for it.

Step 4: prove it works

Never assume a cache is working. Make a test that asserts the database is not touched. Hibernate's statistics expose second level hits and misses:

src/test/java/dev/javahacks/catalog/SecondLevelCacheTest.javajava
@SpringBootTest
@Testcontainers
class SecondLevelCacheTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");

    @Autowired EntityManagerFactory emf;
    @Autowired CountryRepository countries;

    @Test
    void secondLookupInANewSessionIsServedFromTheCache() {
        countries.saveAndFlush(new Country(1L, "VN", "Vietnam"));
        Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
        emf.getCache().evictAll();
        stats.clear();

        loadCountryInNewSession(1L);          // miss: goes to the database and populates the cache
        loadCountryInNewSession(1L);          // hit: no SQL

        assertThat(stats.getSecondLevelCacheMissCount()).isEqualTo(1);
        assertThat(stats.getSecondLevelCacheHitCount()).isEqualTo(1);
        assertThat(stats.getPrepareStatementCount()).isEqualTo(1);   // one SELECT in total
    }

    private void loadCountryInNewSession(Long id) {
        try (var em = emf.createEntityManager()) {
            assertThat(em.find(Country.class, id)).isNotNull();
        }
    }
}

The second lookup happens in a brand new EntityManager, which has an empty first level cache, so a hit can only come from the second level. getPrepareStatementCount confirms the claim at the level that matters: JDBC statements prepared. The same trick is the regression test that keeps the cache from silently vanishing when someone removes an annotation. Statements counted in other ways are in logging SQL and counting statements.

You can also see it in the SQL log. With spring.jpa.show-sql=true the first find prints a select and the second prints nothing.

Caching to-one associations

The most valuable effect of an entity cache is not find calls in your code but association loads. A Product has a lazy origin. When code touches product.getOrigin().getName(), Hibernate initialises the proxy by loading Country by id. With Country cached, that is a memory read, not a query, so a page that lists two hundred products and shows each origin goes from 201 statements to one, with no change to the query. This is the case where the second level cache and the N plus 1 problem meet, and it is a legitimate fix for reference data: see the N plus 1 problem and its fixes for the other tools, such as fetch joins and batch fetching, which should usually come first because they work for any data.

Collection caching and its trap

A cached collection stores element ids under the owner's id. Loading product.getTags() from the cache reads the ids, and then, for entity elements, Hibernate loads each element by id, from the entity cache if it is cacheable and from the database if not. So a cached collection of non cacheable entities makes things worse than no cache at all: one fewer query to find the ids, then one query per element. The rule is to cache a collection only when its element type is also cacheable, or the elements are basic values.

The second consequence is invalidation. Any change to the collection, adding a tag, evicts the collection entry for that owner. A collection that changes often has a cache entry that is rarely valid, and the cache is pure overhead.

Natural id caching

@NaturalIdCache on Country stores the mapping from code to id. Then a lookup by business key avoids the query that would otherwise be needed to find the primary key:

java
Country vn = session.bySimpleNaturalId(Country.class).load("VN");

The natural id must be immutable, or the mapping goes stale, which is why the example marks the column updatable = false. The pattern is described in natural ids in Hibernate. In Spring Data you reach it through a custom repository fragment, since derived queries like findByCode are ordinary queries and are not served from this cache.

The query cache

The query cache stores the result ids of a query for a specific set of parameters. It is separate, must be enabled twice, and is the part of the second level cache that disappoints most often. Turn on the property and mark each query as cacheable:

java
public interface ProductRepository extends JpaRepository<Product, Long> {

    @QueryHints(@QueryHint(name = "org.hibernate.cacheable", value = "true"))
    @Query("select p from Product p where p.origin.code = :code order by p.name")
    List<Product> findByOriginCode(@Param("code") String code);
}
YAML
spring.jpa.properties.hibernate.cache.use_query_cache: true

How it stays correct: Hibernate records, in the update timestamps region, the time of the last change to each table. A cached query result carries the time it was stored. On lookup, if any table that the query touches was modified after that time, the result is discarded. The consequence is that any write to the table invalidates every cached query on it, not just queries that would be affected. On a table that is written every few seconds, the query cache hit ratio is close to zero and each query pays the cost of storing results that are immediately dead.

It is worth it in a narrow case: queries over rarely changing tables, repeated with a small set of parameter values. A findByOriginCode over products that change once a day fits. A dashboard query over an orders table does not. Because the query cache returns ids only, the entities themselves should be in the entity cache, or each hit still costs one query per row, the same trap as collections. Decide on evidence: enable it, look at the hit ratio, and turn it off if the ratio is low.

Cache modes: bypassing and refreshing

Sometimes a single operation must ignore the cache, for instance an admin screen that must show the true database state, or a job that loads a lot of data and should not push everything else out. Jakarta Persistence defines two modes, set per operation or per session:

java
Map<String, Object> hints = Map.of(
        "jakarta.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS,
        "jakarta.persistence.cache.storeMode", CacheStoreMode.REFRESH);

Product fresh = em.find(Product.class, id, hints);

CacheRetrieveMode.BYPASS skips reading the cache. CacheStoreMode.REFRESH writes the freshly loaded state back, replacing a possibly stale entry, while BYPASS as the store mode leaves the cache alone, the right choice for a batch read of millions of rows. Manual eviction is available through the standard API:

java
Cache cache = emf.getCache();
cache.evict(Product.class, id);       // one entity
cache.evict(Product.class);           // every Product
cache.evictAll();                      // everything, including query results

Expose a protected admin operation that calls these, because the day will come when a data fix is applied directly in the database and the application must be told.

Consistency: what invalidates what

Hibernate keeps the cache correct only for changes it knows about. Know the list.

Writes through entities update or evict the entry as the strategy dictates. That is the case Hibernate handles well.

Bulk JPQL statements such as update Product p set p.price = ... bypass the entity lifecycle. Hibernate does invalidate the affected regions, evicting every cached Product, because it cannot know which rows changed. Correct, but it throws away the whole region, a cost to remember when you run a bulk update frequently. The details of what bulk statements skip are in bulk updates and deletes in JPA.

Native SQL is opaque. By default, a native query that modifies data evicts all second level cache regions, which is safe and drastic. You can narrow it by declaring the tables it touches:

java
em.createNativeQuery("update product set price = price * 0.9 where category_id = :c")
        .unwrap(org.hibernate.query.NativeQuery.class)
        .addSynchronizedEntityClass(Product.class)       // evict only Product, not everything
        .setParameter("c", 12)
        .executeUpdate();

Writes by anyone else are invisible. A second service that shares the database, a DBA fixing a row, an import script run in psql: none of them tell your cache. This is the real boundary of the feature. If another application writes the same tables, either give the regions a short time to live, so staleness is bounded by minutes, or do not cache those entities at all. The TTL in ehcache.xml is not an optimisation, it is your correctness bound.

Several application nodes

Everything above describes one JVM. With four replicas each has its own cache, each warmed independently, and an update handled by node A evicts the entry in node A only. Nodes B, C and D keep serving the old state until their entries expire. For READ_ONLY reference data this is a non issue. For READ_WRITE data that users can see change, it is a visible bug: a customer edits a product, refreshes the page and, depending on which node answers, sees the old or the new version.

There are three ways out. Accept a short TTL. If a minute of staleness is acceptable, a one minute TTL bounds the damage and needs no infrastructure. Use a clustered provider that propagates invalidations or shares the data, which means a different region.factory_class such as Infinispan's, Hazelcast's or a Redis based region factory, with the cost of a network hop per cache access and the operational weight of the cluster; the comparison is in Redis versus Hazelcast versus Infinispan. Or cache only what never changes and keep volatile entities out. For most applications the third option, combined with a Spring-level cache for specific computed answers, is the right size.

If you run only one instance by design, such as a desktop style deployment, the local cache is fully consistent and you can use READ_WRITE without further worry, except for the external writer case above.

Measure the benefit

A cache that does not hit is a memory cost. Statistics tell you whether each region earns its place. Print them for development, and export them in production with Micrometer, which Spring Boot binds to Hibernate automatically when statistics are on:

java
Statistics stats = sessionFactory.getStatistics();
for (String region : stats.getSecondLevelCacheRegionNames()) {
    CacheRegionStatistics r = stats.getDomainDataRegionStatistics(region);
    long total = r.getHitCount() + r.getMissCount();
    double ratio = total == 0 ? 0 : (double) r.getHitCount() / total;
    System.out.printf("%-50s hits=%d misses=%d puts=%d ratio=%.2f%n",
            region, r.getHitCount(), r.getMissCount(), r.getPutCount(), ratio);
}
Text
dev.javahacks.catalog.Country                      hits=48211 misses=3 puts=3 ratio=1.00
dev.javahacks.catalog.Product                      hits=1204 misses=7311 puts=7311 ratio=0.14
dev.javahacks.catalog.Product.tags                 hits=0 misses=912 puts=912 ratio=0.00

That sample output (illustrative figures, not a measurement) shows the three outcomes you will see. Country is the ideal: three misses to warm up, then all hits. Product has a ratio of fourteen percent, which says the working set is larger than the cache or the entries are being invalidated by writes faster than they are read. Raise the size or drop the cache from that entity. Product.tags has zero hits, so the collection cache costs memory and puts for nothing. A reasonable policy: remove the annotation from any region whose ratio stays below about half after a representative period, since each miss on a READ_WRITE region also pays for a put.

With Actuator and Micrometer on, the metrics hibernate.second.level.cache.requests tagged result=hit and result=miss give you the same figures on a dashboard.

The Spring Cache alternative

The second level cache works at the persistence layer and only by id. Often a cleaner approach is caching at the service layer with Spring's cache abstraction, keyed by whatever makes sense, storing DTOs or computed results rather than entities:

java
@Service
public class CountryLookup {
    private final CountryRepository countries;

    public CountryLookup(CountryRepository countries) {
        this.countries = countries;
    }

    @Cacheable(cacheNames = "countryByCode", key = "#code")
    public CountryView byCode(String code) {
        Country c = countries.findByCode(code).orElseThrow();
        return new CountryView(c.getCode(), c.getName());
    }
}
Hibernate L2Spring @Cacheable
Keyed byEntity id or natural idAny method argument
StoresEntity stateWhatever the method returns
Invalidated byHibernate on its own writesYou, with @CacheEvict, or a TTL
Hit savesEntity loads and association initialisationThe whole method, including queries and mapping
SurprisesSilent staleness from outside writesForgotten evictions

They are not exclusive. A reasonable stack for reference data is Hibernate L2 with READ_ONLY for the entities and Spring caching for aggregated answers built from them. If you already use Caffeine at the service layer, Caffeine versus Guava versus Ehcache covers choosing the library.

Projections and DTO queries bypass the entity cache

A related misunderstanding is expecting the cache to speed up projections. A query such as select new dev.javahacks.catalog.ProductView(p.id, p.name) from Product p returns values, not entities, so there is nothing to assemble from the entity cache and it always hits the database. The same holds for Spring Data interface projections. That is fine and often preferable for list screens, where you want narrow rows, but it means the cache helps loads by id and association navigation, not these queries. DTO projections with records shows when narrow queries are the faster option anyway.

Multi tenancy

In a multi tenant application the cache key includes the tenant identifier, so two tenants never share an entry, which is correct by default. The consequence is that cache size has to account for tenants times rows. If one tenant has a million products, a twenty thousand entry limit is shared among everyone and the hot tenant evicts the others. See multi tenancy in Hibernate for how tenancy is identified, and size regions with the biggest tenant in mind.

Troubleshooting guide

When the cache does not behave, work from the symptom:

SymptomLikely causeCheck
No hits at all, SQL on every findEntity not @Cacheable or no @Cache, or L2 disabledProperty use_second_level_cache, annotations, startup log
Hits in tests, misses in productionDifferent sharedCache.mode or region configCompare effective properties on both
Stale value after a direct database changeWriter outside HibernateTTL, manual evict after the change
Stale value on one node onlyPer-node cache, no invalidation propagationCluster provider or short TTL
Can't write to a readonly objectUpdate on a READ_ONLY entitySwitch to READ_WRITE
Memory growth over daysNo expiry or size limit on a regionRegion config, provider statistics
Query cache never hitsTable written constantly, or parameters vary widelyTimestamps region, hit ratio
Hit ratio is high but latency did not improveThe database was not the bottleneckProfile the request before caching more

The last row is the most important lesson. A cache is an answer to a measured problem, and the measurement comes first.

A short decision recipe

If you take only a page from this guide, take this sequence. Find the queries that dominate by count in a real workload, using statistics. Fix the ones that are plain N plus 1 problems with fetch joins and batch fetching. For what remains, identify entities that are read far more than they are written and that nothing outside the application modifies. Mark those READ_ONLY if they never change and READ_WRITE with a TTL if they do. Prove each with a statement count test. Watch the hit ratio for a week and delete the annotation wherever it is not paying. The result is a small, deliberate set of cached entities, not an application where everything is cached and nothing is understood.

A worked scenario: the product catalogue page

Pull the pieces together with a realistic request. A catalogue page lists 50 products, each showing its name, its origin country and its tags, and the same page is requested hundreds of times a minute. The naive implementation loads the products with one query, then touches getOrigin() and getTags() per row. With nothing cached, that is one query for the page, up to 50 for the origins and 50 for the tags: 101 statements per request.

Apply the guide in order. First, fix what needs no cache: a fetch join or batch fetching collapses the origin and tag loads into a handful of statements regardless of whether the data is hot. Say that brings the page to three statements. Second, look at what is left. The product list query is dynamic and changes with every filter, so it is a poor candidate for the query cache. The origins, though, are the same two hundred countries on every page, so marking Country as READ_ONLY removes the origin statements entirely, leaving two. The tags depend on the products, which change when editors work, so a READ_WRITE collection cache would be invalidated by every edit. Measure first: if editors change a product twice a day and the page is requested a thousand times an hour, the collection hit ratio will be excellent and the cache is worth keeping; if the catalogue is edited constantly, drop it.

The lesson is the order of operations. The cache removed one statement from a page that had already been cut from 101 to three by fixing the query shape, and for the product list itself it does nothing. That is a typical outcome, and it is why this guide keeps repeating that the cache is the last step and the measurement is the first.

Frequently met questions

**Does find always use the cache?** Only if the entity is cacheable and the session's retrieve mode is USE, the default. A JOIN FETCH query does not consult the entity cache for the fetched rows; it reads the joined result and may populate the cache with it.

**Can the cache hold entities with @Version?** Yes, and it works well with READ_WRITE, because the version is part of the stored state. The optimistic lock check still happens in the UPDATE statement against the database, so a stale cached version results in a conflict exception and not a lost update. The interaction is covered in optimistic locking with a version column.

**Does it work with @Transactional(readOnly = true)?** Yes. Reading from the cache is allowed in read only transactions, and populating it on a miss still happens.

What about Hibernate Envers or soft deletes? Audited tables are poor cache candidates because they grow and are read rarely. Soft deleted rows still sit in the table, so a cached entity can represent a row that business rules consider gone; check that your filter is applied on cache hits, which @SQLRestriction does not guarantee for lookups by id.

Will it survive an application restart? With the heap based providers shown here, no. The cache starts empty and warms up. A disk tier in Ehcache can persist entries across restarts, at the price of more configuration and the risk of loading stale data after a deployment that changed the entity shape.

Does the cache break after an entity class changes? The stored array follows the old property order. In-memory caches are rebuilt on every restart, so a new deployment starts clean. This is another reason clustered or persistent caches need a version in the key or a flush on deploy, as discussed in the section on several nodes.

Failure modes

Caching volatile entities. An entity updated several times a minute spends its life in soft locks and evictions. The cache adds work and returns misses. Cache what is read many times per write.

**READ_ONLY and an update.** An update to a read only entity fails at flush with UnsupportedOperationException: Can't write to a readonly object. If your "reference data" turns out to change, switch to READ_WRITE rather than removing the check.

Missing region configuration. An entity cached without a configured region uses provider defaults, which may mean no expiry and no size limit, so memory grows without bound. Configure every region and check the startup log for "missing cache" warnings.

Caching large graphs. An entity with large text or binary columns makes each entry big. A twenty thousand entry limit means little when entries weigh 100 KB. Size by bytes where the provider supports it, or do not cache such entities.

Detached entities and lazy fields. A cache hit builds an entity from stored state; lazy associations still load on access. The cache does not remove the need to fetch related data inside the session, and a LazyInitializationException is still possible outside it.

Double caching. A Spring @Cacheable over a method that loads cached entities holds the data twice. Pick one layer for each piece of data.

Tests that pass for the wrong reason. A test suite that never clears the cache between tests sees data from earlier tests. Evict in a @BeforeEach with emf.getCache().evictAll().

Operating it

Before enabling in production, run through a short checklist. Every cached entity has a deliberate strategy and a region with a size and a TTL. The startup log shows no missing region warnings. A test asserts the hit and statement counts for the one lookup you care about. The statistics or Micrometer metrics are on a dashboard, with an alert on a collapsing hit ratio. Writers outside the application are known, and their tables are either excluded or given a TTL that matches how long staleness is tolerable. And there is a documented way to evict, because someone will need it.

When this does not apply

If the same rows are read once and never again, no cache helps. If your bottleneck is a missing index or a bad query plan, fix that first; a cache in front of a slow query only hides it until a miss. Reading a slow query plan is the tool for that. If correctness requires always reading the latest committed value, such as balances or stock, do not cache it. And if the number of distinct rows is far larger than any memory you can give the cache, the hit ratio will be low by arithmetic, and a read replica or better indexing is the answer. For the primary sources, read the Hibernate user guide chapter on caching, the JCache specification overview and the Ehcache 3 documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.