flush() method in Hibernate

flush(): 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.

Example on flush() method

Database

  •  After session.flush(), hibernate compares employee object data and corresponding record in database. If there is a difference it will execute update query to update object data in the database, but it will not commit.
  • After transaction.commit(),  Here also , hibernate compares employee object data and corresponding record in database. If there is a difference it will execute update query to update object data in the database, and commits transaction.
  • session.flush() must be called before committing the transaction and closing the session.

Batch Processing with flush() method

Consider a requirement when you want to insert a large number of records in database using Hibernate. The code looks like as below.

This code may throw OutOfMemoryError somewhere around 50,000th row. Because Hibernate caches all the newly inserted Employee objects in  the session level cache. We can solve this problem using hibernate batch processing.

We need to set hibernate.jdbc.batch_size in hibernate.cfg.xml as below

So, Hibernate executes every 40 rows as a batch.

And the above code has to be changed to :

Batch processing helps to avoid OutOfMemoryError

 

Posted in hibernate and tagged , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">