Video in progress
What is Hibernate's first-level cache?
It is the persistence context itself: entities loaded by id within one session are kept here. It is always on, can't be turned off, and disappears when the session closes.
📖 Answer
@Transactional
public void sample() {
Book b1 = em.find(Book.class, 7L); // SELECT
Book b2 = em.find(Book.class, 7L); // no SELECT
}
The second find doesn't go to the database. But no other transaction or user sees this cache: every session has its own.
A point where many people get it wrong: a JPQL query bypasses this cache.
Book b3 = em.createQuery("select b from Book b where b.id = 7", Book.class)
.getSingleResult(); // the SELECT is sent anyway
The query is sent to the database. Only when the result comes back does Hibernate see, by the row's id, that the context already has an object, and it returns that one (it does not overwrite it with the fresh data).
Because of this, if you re-read a row within one transaction that another application or a native SQL statement has changed, you may see the old value. If you need the new one, use em.refresh(entity).
Sign up to mark studied questions and save your progress.