Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
Chaturmind
← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 8+ Years (Senior & Lead)JPA, Hibernate & Databases at Scale
✓ FreeAdvanced· 8 min read

Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions

First-level vs second-level cache, enabling L2 caching (providers, annotations, regions, concurrency strategies), whether L2 is shared across sessions, when the query cache helps (and its parameter handling), evicting entities/regions, Spring @Cacheable vs Hibernate caches, consistency and stale-data risks, caching lazy associations (collection caches), and monitoring hit/miss statistics in production.

Published September 25, 2026


How to use this lesson

Hibernate caching is frequently misunderstood. The senior message is:

  • the first-level cache is about identity and unit of work, not performance tuning;
  • the second-level cache helps read-mostly reference data;
  • the query cache is rarely worth it;
  • in clustered systems, consistency is the real problem.

Q1. What's the difference between the first-level and second-level cache?

Short answer:

  • First-level (L1) cache = the persistence context:
    • per EntityManager/Session (usually per transaction or request);
    • always on;
    • it guarantees one managed instance per ID (em.find twice returns the same object, without a second SELECT), and enables dirty checking and write-behind (the SQL is flushed at commit);
    • it's discarded when the session closes.
  • Second-level (L2) cache:
    • optional, and configured per entity or collection;
    • shared across sessions, within the SessionFactory (the application instance, or the cluster with a distributed provider);
    • it stores dehydrated entity state (field values, not objects), keyed by ID;
    • it's consulted before hitting the database on find and lazy-association loads.

Learn it in depth → Caching Strategies

Q2. How do you enable the second-level cache? How is it implemented (providers)? Which annotations or configuration enable it?

Short answer:

  1. Add a JCache (JSR-107) provider: hibernate-jcache plus Ehcache 3, Caffeine (through its JCache adapter), Hazelcast or Infinispan (clustered); or a Redis-based integration (Redisson).
  2. Configure it:
spring:
  jpa:
    properties:
      hibernate.cache.use_second_level_cache: true
      hibernate.cache.region.factory_class: jcache
      hibernate.javax.cache.provider: org.ehcache.jsr107.EhcacheCachingProvider
      jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE      # only @Cacheable entities
      hibernate.generate_statistics: true                           # for tuning (with care in production)
  1. Annotate the entities (and collections) to cache:
@Entity
@jakarta.persistence.Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "country")
public class Country { @Id String code; String name; }
  1. Choose a concurrency strategy:
    • READ_ONLY: immutable data; the fastest;
    • NONSTRICT_READ_WRITE: rare updates; brief staleness is acceptable;
    • READ_WRITE: soft locks, giving consistency within one node;
    • TRANSACTIONAL: JTA-capable providers.
  2. Configure the regions in the provider: size, TTL, heap or off-heap.

Q3. Is the second-level cache shared across sessions?

Short answer: Yes. It belongs to the SessionFactory, so every session (transaction) in that application instance shares it. Across multiple instances (pods), each has its own local L2 unless you use a clustered or distributed provider (Hazelcast, Infinispan, Redis-backed). With local caches, one pod's update doesn't invalidate the other pods' copies, which gives stale reads. Use invalidation-based clustering, short TTLs, or only cache effectively immutable data.

Q4. When is the query cache useful? When does Hibernate use it? Can you cache a query with parameters?

Short answer: The query cache stores query results as lists of entity IDs (or scalar values), keyed by the query string plus the parameter values (plus pagination). So yes, parameterised queries are cached, one entry per distinct parameter set. It's used only when:

  • hibernate.cache.use_query_cache=true;
  • and the query is marked cacheable (@QueryHints(@QueryHint(name = "org.hibernate.cacheable", value = "true")), or query.setHint(...)/setCacheable(true)).

Entity results also need the entities in L2, or each cached ID triggers a SELECT (an N+1 from the cache).

It's useful when the same query runs very frequently with few distinct parameters, and the underlying tables rarely change: lookups of countries, categories or configuration. It's harmful otherwise: any insert, update or delete on a queried table invalidates every cached query touching that table (through update timestamps), so write-heavy tables thrash the cache, and add overhead.

Q5. How do you evict an entity or a region from the second-level cache manually?

Short answer: Use the JPA or Hibernate Cache APIs:

Cache cache = entityManagerFactory.getCache();              // JPA
cache.evict(Country.class, "IN");                           // one entity
cache.evict(Country.class);                                 // the whole entity region
cache.evictAll();                                           // everything

SessionFactory sf = entityManagerFactory.unwrap(SessionFactory.class);
sf.getCache().evictCollectionData("com.shop.Order.lines");  // a collection region
sf.getCache().evictQueryRegions();                          // the query cache
sf.getCache().evictRegion("country");

When: after out-of-band changes (bulk SQL, another application writing to the database, data fixes), during deployments with data migrations, or through an admin endpoint.

Q6. Does Spring's @Cacheable affect Hibernate's caches?

Short answer: No, they're independent layers. Spring's @Cacheable caches method return values (for example, DTOs from a service method) in a Spring CacheManager (Caffeine or Redis), keyed by method arguments. Hibernate's L2 caches entity state inside the ORM. So:

  • evicting one doesn't affect the other;
  • caching managed entities in Spring's cache is risky: detached objects, lazy proxies that fail later, and mutation of shared instances. Cache DTOs;
  • you may end up with double caching and double staleness.

Choose deliberately: the Spring cache at the service level for computed or aggregated read models, and Hibernate L2 for frequently loaded reference entities.

Q7. How do caching strategies affect consistency? What's the risk of stale data, and how do you avoid it?

Short answer:

  • The risks:
    • Out-of-band writes (other services, SQL scripts, bulk JPQL updates) aren't seen by L2, so it serves stale entities.
    • Multiple application nodes with local caches diverge.
    • NONSTRICT_READ_WRITE allows short windows of staleness.
    • The query cache returns stale ID lists if invalidation fails.
  • Mitigations:
    • Cache only data owned by this application, that's read-mostly or immutable (READ_ONLY).
    • Use READ_WRITE (soft locks) for consistency on a single node, and clustered invalidation (Infinispan, Hazelcast) for multiple nodes.
    • TTLs, as a backstop.
    • Evict after bulk updates and external changes.
    • Never cache money balances, stock levels, or anything needing strong consistency.
    • Monitor hit ratios and staleness incidents.

Q8. How do you monitor or debug cache hits and misses in production?

Short answer:

  • Hibernate statistics: hibernate.generate_statistics=true gives Statistics.getSecondLevelCacheHitCount(), the miss and put counts, region statistics, and query cache hits. Exposed through Micrometer's Hibernate metrics (hibernate.second.level.cache.requests{result=hit|miss}) when enabled, to Prometheus and Grafana. Statistics have some overhead, so enable them selectively, or sample.
  • Provider metrics: Ehcache, Hazelcast and Infinispan expose JMX or Micrometer statistics (size, evictions, expiry, heap usage).
  • Logging for debugging: org.hibernate.cache=DEBUG, plus SQL logging to confirm that SELECTs disappear.
  • Spring caches: CacheMetricsRegistrar/cache.gets{result=hit|miss} (enable recordStats() for Caffeine).
  • The test: a hit ratio that stays low means the cache adds overhead with no benefit. Remove it.

Q9. Can lazy-loaded associations be cached? What are the caveats?

Short answer: Yes, through the collection cache. Annotate the collection with @Cache(usage = …). It caches the IDs of the collection elements, so the element entities must also be cacheable, otherwise each ID triggers a SELECT (an N+1 from the cache). @ManyToOne targets that are in L2 resolve from the cache when a lazy proxy is initialised.

The caveats:

  • collection caches are invalidated when the collection changes (add or remove through the owning side), but bulk updates or out-of-band changes leave them stale;
  • large collections consume a lot of memory;
  • it doesn't fix LazyInitializationException: you still need an open session to initialise the proxy;
  • ordering or filter clauses (@SQLRestriction) interact with the cached contents.

Q10. When is the second-level cache worth it, overall? (The senior summary)

Short answer: It's worth it when:

  1. the entities are read far more than written;
  2. they're loaded by ID (or through associations) repeatedly, across requests;
  3. this application owns the writes, or staleness is acceptable;
  4. database load or latency is a measured problem.

Otherwise, prefer:

  • query optimisation and projections;
  • application-level caching of DTOs (Spring @Cacheable with Caffeine or Redis) with explicit invalidation;
  • read replicas.

Follow-up questions this topic invites — and their answers

Q: What is the persistence context's role in repeatable reads? A: Within one session, loading the same entity again returns the same instance, with its in-memory state, even if the database changed in the meantime: application-level repeatable read. Use em.refresh() to reload it.

Q: Why can a long-running persistence context cause memory problems? A: Every loaded entity stays managed (plus a snapshot for dirty checking) until the session ends. Batch jobs should flush() and clear() periodically, or use StatelessSession, or projections.

Q: How does READ_WRITE avoid stale reads during updates? A: It puts a soft lock on the cache entry when an update starts. Readers that see the lock go to the database. The lock is replaced by the new state after commit (or expires on failure).

Q: Should you cache entities with lazy associations in Redis through Spring @Cacheable? A: No. Serialising a Hibernate proxy, or an entity graph, is fragile (lazy initialisation errors, huge payloads). Cache purpose-built DTOs instead.

Previous

JPQL vs Native Queries in Depth — Interview Questions

Next

Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions

AI Tutor

Lesson: Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.