The JPA and Hibernate second-level cache

java database orm hibernate jpa cache October 12, 2021

Vlad Mihalcea posted “The JPA and Hibernate second-level cache”, describing the second of the two cache levels Hibernate provides for application developers.

The first-level cache is quite simple, and applies to the current thread and session context, so from most users’ perspectives, it barely acts as a cache at all - it means that if you have a running transaction, repeated fetches of a given entity within the context of that transaction will use a cached element.

The second-level cache is more in line with what people consider a cache to be: it caches entities between transactions (and threads), so repeated reads of an entity don’t necessarily have to hit the database.

Note that caches like this come at a cost: if the data isn’t (at least) read-mostly, a cached entity can become stale, which means you’re working with invalid data. It’s worth noting that there are ways to fix this; Mihalcea’s page goes into this with some depth.

in database hibernate jpa cache java orm

Reading time: 1 minute.