The question that matters before enabling L2 cache is not “can I make it faster” but “can I tolerate stale data, and for how long”. The cache sits between Hibernate and the database, serving data that may have been written by a different JVM process, a batch job, a DBA running a script, or another application instance. Every one of those paths can invalidate the cache without Hibernate knowing. If your answer to the staleness question is “no, I cannot tolerate any staleness” — skip L2 entirely. If the answer is “yes, but only for these entities and within these bounds” — read on.
This post covers what L2 actually stores, how to configure Ehcache 3 as a JCache provider, what changed between Hibernate 6 and 7, the three specific staleness modes that catch production teams off guard, and why the query cache is almost always the wrong additional layer.
Continue reading Hibernate 7 Second-Level Cache: When to Turn It On, How to Configure Ehcache 3, and the Three Ways It Will Stale Your Data