Does Hibernate's query cache invalidate after native SQL or external writes?
0 reputation · 20 Jan 2025, 23:16 UTC
For a low-traffic application, enabling Hibernate's query cache with hibernate.cache.use_query_cache=true and @Cacheable can reduce database round-trips and connection occupancy. The cache stores result identifiers rather than entity state, and Hibernate invalidates those entries only when entity state changes through the ORM session lifecycle. When rows are modified by native SQL, JDBC batch statements, or external tools, automatic invalidation is bypassed, potentially leaving query and second-level cache regions stale until a TTL expires or a manual eviction occurs.
The unresolved decision is whether to accept eventual consistency in exchange for lower database costs, or to disable caching and absorb the added latency and connection usage. This matters most when write paths cannot be fully centralized through the ORM. Behavior may also differ across Hibernate major versions and between bulk HQL statements and native SQL, so the exact write path should be tested.
Can the query cache be configured to remain consistent when some writes bypass the ORM, or must architects choose between stale reads and higher database load? Which cache provider settings or invalidation strategies are appropriate for a low-traffic workload with mixed write paths? Does Hibernate provide a documented mechanism to detect or refresh stale query cache regions after out-of-band updates?