Hibernate Second Level Cache: When and How to Use It
In this article
- Background: What the Second-Level Cache Actually Is
- How It Works: Regions, Strategies, and Providers
- When to Use It: The Right Conditions
- How to Configure It Step by Step
- Common Problems and Misconceptions
- Comparing L2 Cache to First-Level and Query Cache
- Costs and Trade-offs
- Safety and Eviction
- Alternatives to L2 Cache
- Frequently Asked Questions
Use Hibernate's second-level cache when you have read-heavy, mostly static data that is shared across sessions and you need to reduce database load. Enable it by adding a cache provider (like Ehcache or Infinispan), annotating entities with @Cache, and configuring the cache region and concurrency strategy.
Background: What the Second-Level Cache Actually Is
Hibernate has two caches. The first-level cache is the Session — it holds entities you've loaded or saved within that session, and it's always on. The second-level cache (L2) sits above that, at the SessionFactory level, meaning it's shared across all sessions in the application. When you load an entity, Hibernate first checks the session cache, then the L2 cache, and only hits the database if both miss.
L2 stores entities, collections, and sometimes query results, but it does not store arbitrary SQL results unless you explicitly use query caching. The cache is a map keyed by entity type and identifier. For example, loading Product with id 42 will look for a key like com.example.Product#42 in the region named com.example.Product.
How It Works: Regions, Strategies, and Providers
To use L2, you need three things:
- A cache provider library (e.g., Ehcache, Caffeine, Infinispan, Hazelcast).
- Configuration in
hibernate.cfg.xmlorapplication.propertiesto enable it and set the provider. @Cacheannotations (or XML mappings) on entities you want cached.
The concurrency strategy determines how the cache handles concurrent access. The four standard strategies are:
- READ_ONLY: for immutable data. Fastest, no locking.
- READ_WRITE: for mutable data where you need consistency. Uses soft locks.
- NONSTRICT_READ_WRITE: for data that is rarely updated. Does not lock, so stale reads possible.
- TRANSACTIONAL: for data that must be consistent with database transactions. Requires a transactional cache provider (e.g., Infinispan).
Example annotation:
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Product {
@Id
private Long id;
// ...
}
For collections (like @OneToMany), you also need to annotate the collection property with @Cache to cache the collection itself.
When to Use It: The Right Conditions
Use L2 when all of these hold:
- Data is read far more often than written (e.g., a lookup table of countries, product categories).
- Data is shared across many sessions — not just per-user.
- You can tolerate some staleness (unless using READ_WRITE or TRANSACTIONAL).
- You have enough heap memory to hold the data without causing GC pressure.
Typical good candidates: reference data, configuration, read-only dictionaries, and entities that are frequently accessed by ID.
Bad candidates: time-sensitive data (e.g., stock prices), data that changes frequently per user (e.g., shopping carts), or entities with complex relationships that are often updated.
How to Configure It Step by Step
- Add a cache provider dependency (e.g.,
org.ehcache:ehcacheororg.infinispan:infinispan-hibernate-cache). - Set properties:
hibernate.cache.use_second_level_cache=trueandhibernate.cache.region.factory_class(or rely on auto-detection). - Annotate entities with
@Cacheand choose a strategy. - Configure cache regions (e.g., in
ehcache.xml) to set TTL, max entries, and eviction policies. - Optionally enable query cache with
hibernate.cache.use_query_cache=trueand callsetCacheable(true)on queries.
For example, Ehcache XML:
<cache alias="com.example.Product">
<expiry><ttl unit="minutes">30</ttl></expiry>
<heap unit="entries">10000</heap>
</cache>
Common Problems and Misconceptions
One big misconception: L2 cache is a replacement for database tuning. It is not; it's a layer on top. Another: enabling L2 automatically caches everything — it doesn't; you must annotate each entity.
Stale data is a real risk. With READ_WRITE, Hibernate uses a version/timestamp to invalidate entries, but if you update the database directly via SQL or another application, the cache becomes stale. You must evict manually using SessionFactory.evict(Class, id) or use a cache that supports timestamp-based invalidation.
Another issue: caching collections can cause performance problems if you cache large collections. Each collection is stored as a separate region, and any change to any element invalidates the whole collection.
Also, the L2 cache is not a distributed cache by default. If you run multiple application instances, each has its own copy, and you need a distributed cache provider (like Hazelcast or Infinispan) to keep them consistent.
Comparing L2 Cache to First-Level and Query Cache
First-level cache is per-session, so it's short-lived and not shared. L2 is per-SessionFactory, shared across sessions. The query cache stores query result identifiers, not the actual entities — it still needs L2 to load the entities. So query cache is only useful if you have L2 enabled and you run the same query repeatedly with the same parameters.
Example: if you run from Product where category='books' often, the query cache stores the list of product IDs. When the query runs again, Hibernate fetches the IDs from cache and then loads each product from L2 or DB. If the underlying data changes, the query cache is invalidated automatically if the relevant tables are updated via Hibernate.
Costs and Trade-offs
The main cost is memory. Each cached entity is a full object graph, so a large cache can cause OutOfMemoryError if not sized properly. Also, cache maintenance adds overhead: checking the cache, serializing/deserializing (if using distributed cache), and managing invalidation.
There's also a development cost: you must carefully choose which entities to cache, configure regions, and handle eviction. And if you get it wrong, you could serve stale data or degrade performance due to cache misses.
Safety and Eviction
To keep data safe, always use READ_WRITE or TRANSACTIONAL for mutable data. For read-only data, use READ_ONLY to avoid overhead. If you update data through Hibernate, it will automatically evict the affected cache entries. But if you use native SQL or external updates, you must manually evict.
Set appropriate TTLs and max sizes in your cache configuration. For example, a TTL of 5 minutes for a product catalog might be fine, but a TTL of 1 hour for a user profile might be too long.
Alternatives to L2 Cache
If L2 seems too complex, consider:
- Using a dedicated in-memory data grid like Redis or Hazelcast for specific hot data.
- Using a view or materialized query in the database.
- Using a CDN or reverse proxy for read-only web content.
- Using a simple
ConcurrentHashMapin your service layer if the data is small and static.
Frequently Asked Questions
Does enabling L2 cache slow down my application?
It can if you cache too much or use a slow provider. But for read-heavy data, it usually speeds things up. The overhead is minimal for small caches.
Can I use L2 cache with Spring Boot?
Yes, Spring Boot integrates with Hibernate's cache. You just add a provider dependency and set properties like spring.jpa.properties.hibernate.cache.use_second_level_cache=true.
How do I clear the entire L2 cache?
You can call sessionFactory.getCache().evictAllRegions() or evictEntity(Class) for a specific entity.
Is L2 cache thread-safe?
Yes, the cache provider handles concurrency. But you must choose the correct concurrency strategy for your data.
What happens if I use READ_ONLY on mutable data?
You'll get stale data and possibly exceptions if Hibernate detects a change. Use READ_ONLY only for truly immutable data.
Can I cache query results without L2?
No, the query cache relies on L2 to store the actual entities. Without L2, query cache is useless.