Hibernate / Hibernate 7 Basics Interview Questions
What is Hibernate's flush behaviour and how does it affect SQL execution?
Flushing synchronises the in-memory persistence context with the database by sending pending SQL. Flush does NOT commit the transaction.
| FlushMode | When SQL sent | Use case |
|---|---|---|
| AUTO (default) | Before queries and at commit | Normal transactional operations |
| COMMIT | Only at commit | Read-heavy operations |
| ALWAYS | Before every query | Strict consistency required |
| MANUAL | Only explicit session.flush() | Bulk operations |
// AUTO flush mode (default): Product p = new Product("Laptop", new BigDecimal("999")); session.persist(p); // INSERT scheduled, NOT sent yet // Query triggers flush in AUTO mode: Long count = session.createQuery("SELECT COUNT(p) FROM Product p", Long.class) .getSingleResult(); // INSERT flushed first so count is accurate // Explicit flush: session.flush(); // sends SQL but does NOT commit // Check for pending changes: session.isDirty(); // true if unflushed changes exist // SQL ordering at flush: INSERT -> UPDATE -> DELETE // Prevents FK constraint violations
More Related questions...