Video in progress
When does Hibernate flush under `FlushMode.AUTO`, and how does that affect query results?
Before commit, and before a JPQL/HQL query that is affected by pending changes in the persistence context. That's why an entity you just persisted inside the transaction shows up in the result of the next query.
📖 Answer
@Transactional
public long createAndCount() {
em.persist(new Product("olma"));
// no INSERT yet: it's only in the action queue
return em.createQuery("select count(p) from Product p", Long.class)
.getSingleResult();
}
The query touches the Product table, and so does the pending INSERT. Hibernate flushes first and then sends the count. The result includes the new row.
Hibernate is smart: if the query touches a different table (select count(c) from Customer c), it may not flush. With native SQL it doesn't know which tables are used. In Hibernate 6 it flushes before a native query by default, but the behavior has changed between versions, so at a point that matters it's better to write an explicit em.flush().
Other modes:
COMMIT: flush only on commit. Queries may see the old state, but unnecessary flushes in a big transaction are reduced.- Hibernate's
MANUALmode: only when you callflush()yourself. Spring switches to exactly this mode in areadOnly = truetransaction.
In practice, knowing when the flush happens helps you understand errors: a unique constraint violation often shows up not on the persist() line but in the next query or at commit, and the stack trace is misleading.
Sign up to mark studied questions and save your progress.