【问题标题】:Grails/Hibernate Batch InsertGrails/Hibernate 批量插入
【发布时间】:2011-07-04 17:17:27
【问题描述】:

我正在使用 STS + Grails 1.3.7 并为数千个域类实例进行批量插入。

这很慢,因为 Hibernate 只是将所有 SQL 语句批处理到一个 JDBC 调用中,而不是将这些语句合并为一个。

我怎样才能把它们变成一个大的声明?

【问题讨论】:

  • 你能发布你插入的代码吗?

标签: sql hibernate grails batch-file insert


【解决方案1】:

你可以做的是每 20 次插入刷新休眠会话,如下所示:

int cpt = 0
mycollection.each{
 cpt ++
 if(cpt > 20){
  mycollection.save(flush:true)
 }
 else{
  mycollection.save()
 }
}

hbernate session 的刷新每 20 次插入执行 SQL 语句。 这是最简单的方法,但您可以在 Tomas lin 博客中找到更有趣的方法。他正在解释你想要做什么:http://fbflex.wordpress.com/2010/06/11/writing-batch-import-scripts-with-grails-gsql-and-gpars/

【讨论】:

    【解决方案2】:

    在域类上使用withTransaction() 方法可以使批处理脚本的插入速度更快。您可以在一个集合中构建所有域对象,然后将它们插入一个块中。

    例如:

    Player.withTransaction{
        for (p in players) {
            p.save()
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以在 Hibernate doc 中看到这一行:

      Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.
      

      当我更改生成器的类型时,它起作用了。

      【讨论】:

        猜你喜欢
        • 2011-02-15
        • 2012-02-16
        • 2015-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多