How to commit batches of inserts in hibernate?

一曲冷凌霜 提交于 2019-12-10 15:19:29

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/13642219/how-to-commit-batches-of-inserts-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!