使用 executeUpdate() 批量更新

问题描述

我想执行批量更新。我使用 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 进行批量更新?

解决方法

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

entityManager.flush()

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

那就试试打电话

entityManager.getTransaction().commit()

看看这是否会改变行为。请注意,交易将无法再回滚,但这应该是显而易见的。

,

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

,

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

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