【问题标题】:Batch insertion using hibernate native queries使用休眠本机查询进行批量插入
【发布时间】:2017-04-06 10:59:50
【问题描述】:

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

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";
            }

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

【问题讨论】:

    标签: java hibernate bulkinsert native-sql


    【解决方案1】:

    首先,如果你想在hibernate中使用正确的JDBC语句批处理,你必须在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

    【讨论】:

      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多