3

下面是在迭代中执行插入查询的代码:

session = sessionFactory.getCurrentSession();

        for (SampleBO items : listCTN) {    
            try {    
                query = session
                        .createSQLQuery("insert into xyx values(.......) where items="+items.getItem());

                OBJLOG.info("query executed is" + query);               
                query.executeUpdate();
                result = "success";
            }

这里查询一个接一个地执行。如何批量执行查询?

4

1 回答 1

2

首先,如果你想在hibernate中使用正确的JDBC statements批处理,你必须在hibernate的配置中设置batch size参数。根据 Hibernate 的文档,“推荐值在 5 到 30 之间”:

hibernate.jdbc.batch_size=30

然后,在您的循环中,您必须在每次插入 X 次时刷新会话(X 应该与为批量大小设置的数字匹配)。它应该如下所示:

int count = 0;
for (SampleBO items : listCTN) {      
    query = session
            .createSQLQuery("insert into xyx values(.......) where items="+items.getItem());
    OBJLOG.info("query executed is" + query);               
    query.executeUpdate();
    result = "success";

    if (++count % 30 == 0){
        session.flush();
        session.clear();
    }
}
//optional - I've seen issues in hibernate caused by not flushing data for the last iteration, for example -  the last 10 inserts.
session.flush();
session.clear();

也可以看看:

https://www.tutorialspoint.com/hibernate/hibernate_batch_processing.htm https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch15.html

于 2017-04-06T11:50:23.910 回答