I have to save a large number of objects to the database using hibernate. Instead of commiting all of them at once, I would like to commit as soon as n (BATCH_SIZE) objects are present in the session.
Session session = getSession();
session.setCacheMode(CacheMode.IGNORE);
for(int i=0;i<objects.length;i++){
session.save(objects[i]);
if( (i+1) % BATCH_SIZE == 0){
session.flush();
session.clear();
}
}
I would have tried something like above, but I read that session.flush()
does not commit the changes to the database.
Is this the following code the correct way to do it?
Session session = getSession();
session.setFlushMode(FlushMode.COMMIT);
session.setCacheMode(CacheMode.IGNORE);
session.beginTransaction();
for(int i=0;i<objects.length;i++){
session.save(objects[i]);
if( (i+1) % BATCH_SIZE == 0){
session.getTransaction().commit();
session.clear();
//should I begin a new transaction for next batch of objects?
session.beginTransaction();
}
}
session.getTransaction().commit();
As far as i can tell your solution is correct.
There might only be one problem: Depending on how you get your sessions from the SessionFactory the commit might also close your session and you would have to open a new one. According to my knowledge this always happens if you use getCurrentSession() and the session context "thread". If you are using openSession() the session seems not to get closed by a commit automatically.
You can easily check this using the isOpen() method after commiting the transaction. If the session get closed you have to open a new one before any further calls to save().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With