Video in progress
What does flush() do and how is it different from commit?
flush() sends the changes accumulated in the persistence context to the database as SQL, but doesn't end the transaction. Commit confirms the transaction, and Hibernate flushes by itself before that. If you roll back after a flush, the changes are still undone.
📖 Answer
After a flush the SQL has been executed in the database, but other transactions can't see it yet (at the usual isolation levels).
When Hibernate flushes by itself (the default FlushMode.AUTO):
- before the transaction commits;
- before running a JPQL/HQL query, if the query touches a table that was modified, so the result is correct;
- before a native query too (in Hibernate 6 in JPA mode).
When you need a manual flush():
em.persist(order);
em.flush(); // to catch the constraint error right here
// or to read a column generated by a trigger or DB default afterwards
Another typical case is large batch processing: flush() and clear() after every 50 records, so memory doesn't fill up.
Keep in mind that DataIntegrityViolationException often shows up not on the save() line but at commit, because that's when the SQL actually goes out. This is misleading when you read the stack trace.
Sign up to mark studied questions and save your progress.