如何在hibernate中提交批次的插入? [英] How to commit batches of inserts in hibernate?

查看:170
本文介绍了如何在hibernate中提交批次的插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用hibernate将大量对象保存到数据库中。
而不是一次提交所有这些对象,只要n(BATCH_SIZE)对象出现在会话中,我就想提交。

  Session session = getSession(); 
session.setCacheMode(CacheMode.IGNORE);
for(int i = 0; i< objects.length; i ++){
session.save(objects [i]); ((i + 1)%BATCH_SIZE == 0){
session.flush();
if
session.clear();
}
}

我会尝试类似上面的内容,但我读过 session.flush()不会将更改提交到数据库。
这是下面的代码正确的方法吗?

  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]); $(b + b)if((i + 1)%BATCH_SIZE == 0){
session.getTransaction()。commit();
session.clear();
//我是否应该为下一批对象开始新的事务?
session.beginTransaction();
}
}
session.getTransaction()。commit();


解决方案

据我所知,您的解决方案是正确的。

可能只有一个问题:
根据您从SessionFactory获得会话的方式,提交也可能会关闭会话,您必须打开新的一个。据我所知,如果使用getCurrentSession()和会话上下文thread,这总是会发生。如果您使用的是openSession(),会话似乎不会自动被提交关闭。



在提交事务后,您可以使用isOpen()方法轻松检查。如果会话关闭,您必须在再次调用save()之前打开一个新的。


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

这篇关于如何在hibernate中提交批次的插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆