The second-level cache (2nd-level cache) is an optional, shared Hibernate cache that stores entities (and sometimes collections) beyond the scope of a single session — allowing data to be reused across multiple sessions in the same application, which can dramatically improve performance.
🔹 Key characteristics:
✅ Unlike the first-level cache (session-scoped, mandatory), second-level cache is session factory-scoped and optional.
✅ Stores entity data in memory or distributed caches (e.g., Ehcache, Infinispan, Redis).
✅ When enabled, Hibernate first checks the second-level cache before querying the database for an entity.
✅ Helps reduce database load by serving frequently accessed data from cache, especially in read-heavy applications.
🔹 How it works:
- When you load an entity in Hibernate, if second-level cache is enabled:
- Hibernate first checks the first-level cache (session).
- If not found, it checks the second-level cache (shared across sessions).
- If still not found, it queries the database, then stores the result in both caches.
- This flow allows multiple sessions (and even different application nodes) to reuse cached data.
🔹 Basic example of enabling second-level cache with Ehcache:
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
...
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
</session-factory>
</hibernate-configuration>
Entity class:
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
@Id
private Long id;
private String username;
}
🔹 Common second-level cache providers:
- Ehcache (most widely used)
- Infinispan
- Redis (via plugins)
- OSCache
🔹 What can be cached:
✅ Entities
✅ Collections (e.g., lists, sets in one-to-many mappings)
✅ Query results (using query cache)
✅ Key takeaway:
Second-level cache is a shared, optional cache in Hibernate that stores entities beyond individual sessions, reducing database load and improving performance for repeated reads of frequently used data.