Java.Hibernate.Medium.What is the purpose of Session.flush()?

Short Answer

Session.flush() synchronizes the state of the in-memory persistent entities with the database by executing pending SQL statements, but it does not commit the database transaction.


🔎 Detailed Explanation

  • In Hibernate, when you make changes (insert, update, delete) to persistent entities, these operations are queued in the session’s internal cache (called the persistence context) and not immediately written to the database.
  • The Session.flush() method forces Hibernate to execute the SQL statements needed to bring the database up to date with the current state of the entities in memory.
  • Flushing ensures the database reflects the most recent changes before certain actions, such as:
    • Before committing a transaction.
    • When executing queries (Hibernate might auto-flush to ensure query consistency).
    • When explicitly calling session.flush().
  • Important: flush() doesn’t end or commit the transaction — it just synchronizes data. A rollback after flush can still undo the changes in the same transaction.
  • Hibernate’s flush modes determine when automatic flushing happens:
    • FlushMode.AUTO (default): flushes before transaction commit or queries if necessary.
    • FlushMode.COMMIT: flushes only before transaction commit.
    • FlushMode.MANUAL: flush only when explicitly called.

🧑‍💻 Code Example

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

MyEntity entity = session.get(MyEntity.class, 1L);
entity.setName("Updated Name");

session.flush(); // Executes SQL UPDATE for the change above

tx.commit(); // Actually commits the transaction
session.close();

📊 Quick Comparison: flush() vs commit()

MethodWhat it doesWhen changes become permanent
session.flush()Synchronizes in-memory state → databaseChanges are not permanent until commit
transaction.commit()Commits the DB transaction, making changes permanentChanges become permanent

💡 Extra Insight: Why explicit flush is useful

  • You might call flush() manually when you need the database to reflect changes before executing a query that depends on those changes.
  • Example: updating a user’s status and immediately running a query that selects active users — flushing ensures your update is visible in the query result.

📌 Key Takeaways

Session.flush() syncs in-memory changes to the database by executing pending SQL.
✅ It doesn’t commit the transaction; data is not permanent until commit.
✅ Use explicit flush when you need consistent read-after-write behavior within a transaction.
✅ Understand flush modes (AUTO, COMMIT, MANUAL) to control Hibernate’s flush timing.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.