What's the use of session.flush() in Hibernate

CHANTI picture CHANTI · Jul 10, 2010 · Viewed 194.4k times · Source

When we are updating a record, we can use session.flush() with Hibernate. What's the need for flush()?

Answer

Pascal Thivent picture Pascal Thivent · Jul 10, 2010

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

  • before some query executions
  • when a transaction is committed

Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).