【问题标题】:Batch update with executeUpdate()使用 executeUpdate() 批量更新
【发布时间】:2021-09-03 19:02:29
【问题描述】:

我想执行批量更新。我使用 JPA 和 Hibernate 5 作为 JPA 提供程序,并具有以下代码:

for (int i = 0; i < entities.size(); i++) {
    if (i > 0 && i % JpaSettings.BATCH_SIZE == 0) {
        entityManager.flush();
        entityManager.clear();
    }
    ....
    count = count + entityManager.createQuery(criteria).executeUpdate();
}
entityManager.flush();
entityManager.clear();

但是,此代码似乎不执行批量更新。因为例如,当我插入时,我会在日志中看到如下内容:

DEBUG org.hibernate.engine.jdbc.batch.internal.BatchingBatch - Executing batch size: 2

但我在更新操作后没有看到此消息。谁能说如何使用 executeUpdate 进行批量更新?

【问题讨论】:

  • 如果可能的话,我认为你应该找到一种方法在多个查询上执行更新。
  • 您是否在代码中的某处更新了 i?条件查询有什么作用?
  • 您期望什么样的批处理?通过批处理人们通常是指批处理插入,但您的示例似乎明确执行 DML 语句。 Hibernate 不能批处理 DML 语句,因为 API 总是必须返回更新计数,这需要立即执行语句。
  • 您对 ID 使用哪种策略? stackoverflow.com/questions/63831206/…
  • 批量大小参数似乎设置为 0,正如Documentation 所说,它依赖于 JDBC2 策略。

标签: java hibernate jpa


【解决方案1】:

如果您没有启用自动提交,您可能只会在该会话中看到数据。

entityManager.flush()

将数据发送到数据库并为您的会话保留,但在事务上下文中。因此,如果事务未提交或回滚或客户端被终止,事务的数据将不会以事务方式持久保存到表中,因此您将无法访问它。

所以尝试调用

entityManager.getTransaction().commit()

看看这是否会改变行为。注意事务不能再回滚,但这应该很明显。

【讨论】:

    【解决方案2】:

    使用.executeUpdate() 无法做到这一点,因为当您调用此方法时,hibernate 将执行此 sql 语句以获取修改的行数。因此,无法使用.executeUpdate() 进行批量更新。

    【讨论】:

      【解决方案3】:

      这可以通过 EniityManager 使用 Session 操作来实现 - 持久化或为实体类的持久化实例设置更新值。

      for (int i = 0; i < entities.size(); i++) {
          if (i > 0 && i % JpaSettings.BATCH_SIZE == 0) {
              entityManager.flush();
              entityManager.clear();
          }
          ....
          entityManager.persist(obj);
      }
      entityManager.flush();
      entityManager.clear();
      

      至于更新的记录数,您可以查看数据库日志中执行的查询。

      执行批量更新时需要注意的一件事是属性 - hibernate.order_updates 和 hibernate.batch_versioned_data 需要设置为 true。下面的博客对此进行了演示。

      博客:https://www.baeldung.com/jpa-hibernate-batch-insert-update

      【讨论】:

        猜你喜欢
        • 2010-09-23
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多