Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to commit batches of inserts in hibernate?

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();
like image 366
atripathi Avatar asked Nov 12 '22 16:11

atripathi


1 Answers

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

like image 150
Werzi2001 Avatar answered Nov 15 '22 05:11

Werzi2001