Java.Hibernate.Medium.So, if flush some updates i update the database, then when i commit a update again ?

Short Answer

No — when you call flush(), Hibernate executes the SQL statements immediately, so the updates are sent to the database once.
When you later call commit(), it finalizes the transaction — it does not re-send updates, but makes the already-executed changes permanent in the database.


🔎 Detailed Explanation

  • flush() causes Hibernate to send pending SQL updates/inserts/deletes to the database right now.
    ✅ The database rows are modified at this point, but the changes are part of the current uncommitted transaction.
  • After flush(), you can:
    • Continue working with the session and make more changes.
    • Roll back the transaction → any flushed changes will not be persisted (they’ll be undone).
  • commit() does not re-execute updates — it just tells the database: “Make all changes since the transaction began permanent.”
  • So in a typical workflow:
    1️⃣ Modify entity → Hibernate queues the change.
    2️⃣ Call flush() → SQL runs → database rows updated.
    3️⃣ Call commit() → transaction finalizes → changes are now permanently saved.
    4️⃣ If instead you call rollback(), flushed updates are reverted.

🧑‍💻 Example Timeline

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

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

// At this point: no SQL executed yet

session.flush(); 
// SQL UPDATE is executed → row in DB is updated inside the transaction
// But transaction is still open → changes are not yet permanent

tx.commit(); 
// The transaction commits → changes are permanently saved in DB

session.close();

🔴 Important: If you replace tx.commit() with tx.rollback(), the update done by flush() will be undone.

📌 Key Takeaways

flush() sends SQL statements to the DB once, updates the rows.
commit() doesn’t re-update, it finalizes all changes done during the transaction.
✅ Changes are only permanent after commit(), even if flush() already updated the DB rows.
✅ A rollback will undo flushed but uncommitted changes.

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

Leave a Reply

Your email address will not be published.