Hibernate Cache Strategies: Types and How to Choose
In this article
Hibernate supports two main cache strategies: first-level caching, which is always on and scoped to a single session, and second-level caching, which is optional and shared across sessions. Within second-level caching, the key strategy choice is the concurrency strategy for each entity or collection—read-only, read-write, nonstrict-read-write, or transactional—plus the query cache, which stores query result sets separately. Choosing the right combination depends on how often data changes, whether stale reads are acceptable, and how many sessions need the same data.
First-Level Cache: Always On, Never Optional
The first-level cache is Hibernate's session-level persistence context. Every entity loaded or saved through a Session is stored there, and repeated get() or load() calls for the same identifier return the same managed instance without hitting the database again. This cache is not configurable in the sense of being enabled or disabled; it is a core part of how Hibernate tracks entity state and dirty checking. It is cleared when the session closes, when clear() is called, or when a query triggers a flush that changes the persistence context.
A common misconception is that first-level caching can be turned off to force fresh reads. It cannot be disabled, but its effect can be bypassed by evicting specific entities, using a new session, or running a query with setCacheable(false) on the query cache. The first-level cache is also why two get() calls in the same transaction return the identical Java object reference—useful for identity and equality, but a source of confusion when developers expect a fresh database read each time.
Second-Level Cache: Shared Across Sessions
The second-level cache is optional and sits at the SessionFactory level, so multiple sessions and transactions can reuse the same cached data. It is enabled with hibernate.cache.use_second_level_cache=true and requires a cache provider such as Ehcache, Infinispan, Hazelcast, or Caffeine (through a JCache integration). Crucially, enabling the cache does not automatically cache every entity; each persistent class or collection must be marked as cacheable, either with @Cacheable and @Cache annotations or with a mapping file entry.
The second-level cache stores entity data by identifier and, for collections, the collection contents. It does not store arbitrary query results unless the query cache is also enabled. This distinction matters: a common mistake is to assume that enabling second-level caching makes session.createQuery("from Book").list() faster. It does not, because the query still executes against the database unless the query itself is marked cacheable and the query cache is active.
Concurrency Strategies for Second-Level Cache
Hibernate defines four concurrency strategies for second-level cached entities and collections. They describe how the cache handles concurrent access and what consistency guarantees are provided. The strategy is set per entity or collection, so a single application can mix strategies where appropriate.
- Read-only: For data that never changes after it is loaded, such as reference tables, country codes, or immutable configuration. It offers the best performance because no locking or version checking is needed. If the underlying data does change, the cache will serve stale values indefinitely until evicted.
- Read-write: For data that changes but where strict consistency is required. Hibernate uses soft locks and version numbers to prevent concurrent updates from corrupting the cache. It is the safest general-purpose strategy but carries more overhead than read-only.
- Nonstrict-read-write: For data that changes occasionally and where a brief window of stale data is acceptable. It does not use strict locking, so concurrent transactions might see slightly outdated values. It is faster than read-write but weaker in consistency.
- Transactional: For full transactional consistency, typically used with a JTA-compatible cache provider. It guarantees that cache updates participate in the same transaction as database updates. It is the most expensive and least commonly used strategy in typical web applications.
These strategies are not interchangeable without thought. Marking a frequently updated entity as read-only will produce stale reads that can be very hard to debug, because the database and cache diverge silently. Conversely, using transactional caching for a static lookup table adds unnecessary overhead.
Query Cache: Caching Result Sets, Not Entities
The query cache stores the identifiers returned by a query, not the entity data itself. When a cached query is re-executed with the same parameters, Hibernate retrieves the list of identifiers from the query cache and then loads each entity from the second-level cache (or the database if not present there). This means the query cache is only useful when the second-level cache is also enabled and the entities involved are cached; otherwise, the query cache saves the SQL parse and execution but still triggers N+1 style loads for the entities.
The query cache is enabled with hibernate.cache.use_query_cache=true and must be activated per query with setCacheable(true). It is invalidated whenever any of the affected tables change, which can make it a poor fit for highly volatile tables. For read-mostly reference data, it can be a significant win; for an orders table with constant inserts, it often adds overhead without benefit.
How to Choose a Strategy
Selecting a cache strategy is a trade-off between performance, consistency, and operational complexity. The following factors usually drive the decision:
- Data volatility: Static or rarely changing data suits read-only caching. Frequently updated data needs read-write or no second-level caching at all.
- Consistency requirements: If stale reads are unacceptable, prefer read-write or transactional strategies, or skip the second-level cache for that entity.
- Access pattern: Entities read many times per write benefit most. Entities written as often as they are read rarely benefit and may suffer from constant invalidation.
- Cluster topology: In a multi-node deployment, the cache provider must support distributed invalidation or replication. A local-only cache can serve stale data on other nodes after an update.
- Memory budget: Caching large entities or collections consumes heap or off-heap memory. A cache that evicts constantly provides little benefit and adds overhead.
A practical starting point is to cache only reference and lookup entities as read-only, leave transactional business entities uncached until profiling shows a bottleneck, and enable the query cache only for specific read-mostly queries that have been measured.
Common Problems and Misconceptions
Several issues recur in projects that adopt Hibernate caching. Recognizing them early saves debugging time.
- Stale data after external updates: If another application or a direct SQL script modifies the database, Hibernate's second-level cache is not aware and will serve old values. Cache invalidation must be handled explicitly or the cache disabled for those tables.
- Assuming the query cache caches entities: It caches identifiers. Without second-level caching, the query cache still results in database reads for each entity.
- Forgetting collection caching: Caching an entity does not automatically cache its collections. Each collection must be marked cacheable, and collection updates have their own invalidation behavior.
- Over-caching in a cluster: A cache provider configured for local caching in a multi-node environment can produce inconsistent reads across nodes. Distributed caching or a short TTL is needed.
- Ignoring the first-level cache: Bulk updates and native queries bypass the persistence context, so entities already in the session may become out of sync. Clearing the session or using
session.evict()after bulk operations is often necessary.
Frequently Asked Questions
Can I disable the first-level cache in Hibernate?
No. The first-level cache is the persistence context and is fundamental to Hibernate's entity management. You can avoid reusing a session, evict individual entities, or clear the session, but you cannot turn the first-level cache off as a configuration option.
Does enabling second-level cache automatically cache all entities?
No. Each entity and collection must be explicitly marked as cacheable. Enabling the cache provider only makes the infrastructure available; without per-entity configuration, nothing is stored in the second-level cache.
What is the difference between read-write and nonstrict-read-write?
Read-write uses soft locks and version checks to maintain strict consistency, while nonstrict-read-write allows a small window where concurrent transactions might read slightly stale data. Nonstrict is faster but weaker; read-write is safer for data that must stay consistent.
Is the query cache useful without second-level cache?
It has limited value. The query cache stores identifiers, so without second-level caching each entity still requires a database load. The query cache mainly saves query parsing and execution, not the entity retrieval cost.
When should I avoid second-level caching entirely?
For entities that are updated frequently, for tables modified by external processes, or when strict real-time consistency is required. In those cases the overhead and risk of stale data usually outweigh the performance gain.