Video in progress
When a native `UPDATE` query runs, what does Hibernate do to the second-level cache?
Hibernate doesn't know which tables a native SQL statement touches, so to be safe it clears the entire L2 cache (all entity and collection regions). To avoid that, you tell it which entities are affected with NativeQuery.addSynchronizedEntityClass() or addSynchronizedQuerySpace().
📖 Answer
This happens on prod: the L2 cache is on, the hit rate is good, and then someone adds a small native query to a job that runs every minute:
em.createNativeQuery("update session_log set processed = true where created_at < :d")
.setParameter("d", cutoff)
.executeUpdate();
After that the hit rate drops sharply and the database load goes up. The reason: Hibernate doesn't analyze this SQL, and assuming the cached data might be stale, it invalidates every region. Even reference data with no connection to it, like Country and Currency, gets evicted from the cache.
The fix is to state the scope of impact:
em.createNativeQuery("update session_log set processed = true where created_at < :d")
.unwrap(NativeQuery.class)
.addSynchronizedEntityClass(SessionLog.class)
.setParameter("d", cutoff)
.executeUpdate();
Now only the SessionLog region (and the query cache entries tied to it) is cleared. If the table doesn't belong to any cached entity, you give the table name with addSynchronizedQuerySpace("session_log"), and the other regions aren't touched.
With JPQL/HQL bulk queries this problem is smaller: Hibernate knows which entity it is and clears only that region.
For diagnostics, watching the per-region put/hit/miss counts in Hibernate statistics is enough: after an invalidation, put jumps sharply. If another service or a DBA changes the database directly, the cache has no idea at all, and that's a separate problem, solved with a TTL.
Sign up to mark studied questions and save your progress.