Video in progress
What is the difference between flush and commit in Hibernate, and when does a flush happen automatically?
Flush sends the changes in the persistence context to the database as SQL, but the transaction is still open, so you can still roll back. Commit finishes the transaction. With FlushMode.AUTO, a flush happens before commit and before a query that touches the changed tables.
📖 Answer
Put simply: flush means "send the SQL", commit means "make it final". Other transactions (under READ COMMITTED) don't see changes that were flushed but not committed. People often get this wrong in interviews: they think that once it's flushed, it's in the database for good.
By default (AUTO) Hibernate flushes:
- before the transaction commits;
- before a JPQL/HQL query runs, if the query touches a table that has unwritten changes;
- before a native SQL query (Hibernate doesn't know which table it touches; in JPA mode it plays it safe and flushes);
- when
flush()orsaveAndFlush()is called by hand.
In practice it feels like this:
@Transactional
public void register(User u) {
userRepository.save(u); // the INSERT may not have been sent yet
// if a unique constraint is violated, the error doesn't appear here...
auditService.write(u);
} // ...it appears in the flush before the commit
DataIntegrityViolationException appears at the end of the method, inside the proxy, and slips past the place where you put your try/catch. If you need to catch the error right there, use saveAndFlush().
Other cases:
- in big batches,
flush()+clear()after every N records frees memory; - with an IDENTITY generator,
persist()does the INSERT immediately because it needs the id. That isn't a flush, but it looks like one; FlushMode.COMMITturns off the flush before queries: faster, but a query doesn't see data that hasn't been written yet.
Sign up to mark studied questions and save your progress.