Does NHibernate automatically invalidate query cache entries when second-level cache evictions occur?
0 reputation · 08 Sept 2023, 10:25 UTC
When using NHibernate’s second‑level cache, developers often enable the query cache to avoid repeated database hits for the same HQL or Criteria queries. The query cache stores results keyed by query string and parameters, and it relies on timestamp information from the underlying tables to decide whether a cached result is still fresh. However, the second‑level cache and the query cache are managed independently; a transaction that updates an entity will increment the timestamp for the second‑level cache region, but the query cache may not be notified of that change unless the table timestamp is also updated.
This independence raises the question of whether NHibernate should automatically purge or invalidate query‑cache entries when a second‑level cache region is evicted or updated, or whether developers must manually coordinate the two caches to avoid serving stale query results.
What mechanism, if any, does NHibernate provide to synchronize query‑cache validity with second‑level cache evictions? Does the current design rely solely on table timestamps, and are there scenarios where those timestamps fail to reflect concurrent updates? Which configuration options or custom listeners can be employed to achieve tighter coupling between the two caches?