Monica Monica - 1 month ago 5
Java Question

Why we need flush in hibernate?

I have recently started with hibernate 3.x and I am confused about the statement "Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database".

Please help me to understand the below points -

  1. flush synchronize the in-memory state of the Session with the database What does it mean does it mean that query for example insert statement is executed and the data is saved into the table but we could not see the data in other session.

  2. After flush where this data will be resides in session object or in database table itself.

  3. How about the exception scenario occurs in case of any exception.

Please help me to understand the working of flush with an example.


Forces the session to flush. It is used to synchronize session data with database. When you call session.flush(), the statements are executed in database but it will not committed.

If you dont call session.flush() and if you call session.commit() , internally commit() method executes the statement and commits.

So commit()= flush+commit.

So seesion.flush() just executes the statements in database (but not commits) and statements are NOT IN MEMORY anymore. It just forces the session to flush.

Flush mainly used when you are dealing with thousands and millions of records. So while dealing with such number of records we use batch update and flush.

Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Employee emp = new Employee(.....);;

In above example if you do not call flush it may throw OutOfMemoryError.

You can check out this post about flushing