Hibernate / Hibernate 7 Basics Interview Questions
What is the second-level cache in Hibernate 7 and how does it work with StatelessSession?
The second-level cache is an optional cross-session application-wide cache. Hibernate 7 changes StatelessSession's behaviour: it now reads/writes the L2 cache by default (was bypassed in v6).
| Aspect | First-level cache | Second-level cache |
|---|---|---|
| Scope | Per Session | Per SessionFactory (application lifetime) |
| Mandatory | Yes | Optional |
| Shared across sessions | No | Yes |
| Provider | Built-in | Infinispan, Ehcache 3, Caffeine |
// Enable L2 cache on an entity: @Entity @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Country { @Id private Long id; private String name; } // Spring Boot 4 configuration: // spring.jpa.properties.hibernate.cache.use_second_level_cache=true // HIBERNATE 7: StatelessSession now uses L2 cache by default! // To bypass (for bulk processing): StatelessSession ss = sf.openStatelessSession(); ss.setCacheMode(CacheMode.IGNORE); // bypass L2 cache
More Related questions...