Hibernate Second Level Cache: How It Works
In this article
Hibernate's second-level cache (L2 cache) is a process-wide cache that stores entity data and collections across sessions, reducing database round-trips for frequently accessed data. It sits between your application and the database, holding objects that survive session closure, so subsequent sessions can load them without hitting the database again.
What Is the Second-Level Cache?
Hibernate has two main caching layers. The first-level cache is the Session cache, which is mandatory and lives only for the duration of a session. The second-level cache is optional, shared by all sessions in a SessionFactory, and stores data in a pluggable cache provider (like Ehcache, Infinispan, or Hazelcast). It caches entity instances (by ID), collections (like a list of child entities), and even query results (with a separate query cache).
Unlike the first-level cache, the L2 cache is not a simple object store. It stores the disassembled state of an entity—essentially the column values—so that it can reconstruct the entity when needed. This avoids holding references to live objects that might be modified concurrently.
How Hibernate Interacts with the L2 Cache
When you call session.get(MyEntity.class, id), Hibernate follows this order:
- Check the first-level (session) cache. If found, return the object.
- If not found, check the second-level cache. If present, deserialize the cached data into an entity instance and store it in the session cache.
- If not present in L2, load from the database, then put the entity into both caches.
For writes, Hibernate updates the database and then invalidates (or updates) the corresponding L2 cache entry. The default behavior is to invalidate on update, meaning the cached data is removed so the next read reloads from the database. Some cache providers support synchronous or asynchronous updates, but invalidation is the safest and most common.
Configuring the Second-Level Cache
To enable L2 caching, you must do three things:
- Add a cache provider dependency (e.g.,
org.hibernate.orm:hibernate-ehcachefor Ehcache 3). - Set
hibernate.cache.use_second_level_cache=true(it is true by default in recent versions, but explicit is better). - Set
hibernate.cache.region.factory_classto your provider's factory (e.g.,org.hibernate.cache.jcache.JCacheRegionFactoryfor JCache-compliant providers).
Then annotate entities with @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) or similar. Without this annotation, the entity is not cached, even if the L2 cache is enabled.
Cache Concurrency Strategies
Hibernate offers four concurrency strategies, each with different guarantees and performance trade-offs:
- READ_ONLY: Use for immutable entities. Fastest, no locking. If a read-only entity is modified, Hibernate throws an exception.
- READ_WRITE: Uses soft locks to ensure that updates are visible to other transactions. Slightly slower but safe for mutable data.
- NONSTRICT_READ_WRITE: No locking; it invalidates the cache on update. Good for rarely updated data where occasional stale reads are acceptable.
- TRANSACTIONAL: Requires a JTA transaction manager and a cache provider that supports transactions (e.g., Infinispan). Guarantees isolation, but adds overhead.
Choosing the wrong strategy can cause data consistency issues. For example, using READ_ONLY on a mutable entity will cause exceptions at runtime.
Common Problems and Pitfalls
One frequent issue is stale data when multiple application nodes share a cache (distributed cache). If one node updates an entity, other nodes may still serve the old value until invalidation propagates. This is a trade-off for performance.
Another problem is memory pressure. Caching too many entities can lead to OutOfMemoryError. Set appropriate maxEntries and eviction policies in your cache provider.
Also, the L2 cache does not cache native SQL queries or projections unless you explicitly enable the query cache. Even then, query results are cached as IDs, not objects, so they still hit the L2 for each entity.
When to Use (and Not Use) the L2 Cache
The L2 cache shines for:
- Reference data (e.g., country codes, status lists) that is read frequently and rarely changed.
- Entities that are heavily read but seldom updated, like product descriptions in an e-commerce site.
- Data that is expensive to load (complex joins, remote database) but small in size.
Avoid L2 caching for:
- High-write entities—the invalidation overhead may outweigh the read benefit.
- Large collections that are frequently modified, as they cause frequent cache evictions.
- Multi-node deployments without a distributed cache, unless you accept stale reads.
Query Cache: A Companion Layer
The query cache is separate from the L2 cache. It stores the results of HQL/JPQL queries as a list of entity IDs. To enable it, set hibernate.cache.use_query_cache=true and call query.setCacheable(true) on each query you want cached. The query cache is only useful if the underlying entities are also cached; otherwise, the IDs still trigger database loads. It also requires that you invalidate the query cache when the underlying tables change—Hibernate does this automatically for entities it manages, but native queries can cause stale results.
Frequently Asked Questions
Does the second-level cache work with native SQL queries?
No, the L2 cache only applies to entities and collections loaded via Hibernate's ORM methods. Native SQL queries bypass the entity cache unless you map the result to an entity and then load that entity via a subsequent session, which would hit the cache.
How do I know if my entity is being cached?
Enable Hibernate's statistics (e.g., hibernate.generate_statistics=true) and log the SecondLevelCacheHitCount and SecondLevelCacheMissCount. If hit count increases on repeated reads, caching works.
Can I cache a collection of child entities?
Yes, annotate the collection (e.g., @Cache(usage = READ_WRITE)) on the mapping. The collection cache stores the IDs of the child entities, not the child objects themselves. When you access the collection, Hibernate loads each child from the L2 or database.
What happens if two transactions update the same cached entity?
With READ_WRITE or TRANSACTIONAL strategies, Hibernate uses locks to prevent dirty reads. With NONSTRICT_READ_WRITE, the last writer wins, and other transactions may see stale data until the cache is invalidated. The exact behavior depends on your cache provider's isolation level.
Is the second-level cache shared across multiple application instances?
Only if you configure a distributed cache provider like Hazelcast or Infinispan. By default, each JVM has its own local cache. For a multi-node deployment, you must use a distributed cache to avoid each node having its own outdated copy.
Does the L2 cache store objects or just data?
It stores the disassembled state (column values), not the actual Java objects. This allows Hibernate to reconstruct a fresh entity instance for each session, avoiding concurrency issues. The cache provider may store this state in serialized form or in memory.