Hibernate: Why should I manually flush() even if I set batch_size in configuration file?

Viewed 3969

I'm learning to use java's hibernate 5.2.10. I started with a few tutorials online but faced the following question.

When using batching, all the tutorials I have seen first set the hibernate.jdbc.batch_size in the configuration file. After that the code is similar to this:

Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<1000000; i++ ) 
{
    Student student = new Student(.....);
    session.save(employee);
    if( i % 50 == 0 ) // Same as the JDBC batch size
    { 
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}
tx.commit();
session.close();

Why should I be doing flush() and clear() manually? Isn't this something that should be done automatically by hibernate since I have already set hibernate.jdbc.batch_size in the configuration file?

For me it seems like I'm batching my operations manually, so why do I have to set the value of hibernate.jdbc.batch_size then?

3 Answers

Answer to your questions you asked in the description, as I have studied it, flush()-ing the batch/transaction is different than commit()-ing the transaction.

You are flushing the transactions after every 50 chunk, means you are synchronizing the transactions to the database as batch of 50. The chunk of 50 has been synchronized with the db but yet to commit.
But when you define the batch-size in configuration file, you are telling the Hibernate to commit the batch of 40 (assume you have set the batch size 40 in conf file.)

Related