使用Spring Data JPA在大量实体上高效执行批量更新

huangapple go评论76阅读模式
英文:

Efficiently Performing Bulk Updates with Spring Data JPA on a Large Number of Entities

问题

我有大量记录需要使用Spring Data JPA高效地进行更新。记录数量在数千条,我当前的方法是使用带有save()方法的循环,速度慢且效率低下。有人可以建议一种更好的方式来执行Spring Data JPA的批量更新吗?

英文:

I have a large number of records that I need to update efficiently using Spring Data JPA. The records number in the thousands and my current approach of using a loop with the save() method is slow and inefficient. Can someone suggest a better way to perform bulk updates using Spring Data JPA?

答案1

得分: 1

spring.jpa.properties.hibernate.jdbc.batch_size=123. 你将在循环中执行更新/插入操作,但Hibernate将尝试将它们批量发送到数据库。

英文:

It is easy done by setting a property:

spring.jpa.properties.hibernate.jdbc.batch_size=123

You will implement the updates/inserts in a loop but Hibernate will try to send them to the database in a batch.

答案2

得分: 1

If you don't need to access the callback from your Repository, you can simply inject the bean entityManager and detach from your Hibernate Context.

private final EntityManager entityManager;

public void someMethod(List<SomeObject> objects) {
    objects.forEach(someObject -> {
        res = someRepository.save(someObject);
        entityManager.detach(res); // or use 'entityManager.clear();' 
    });
}

这可能也会有帮助 使用Spring Data JPA在大量实体上高效执行批量更新

https://stackoverflow.com/questions/75852833/why-is-jpa-hibernate-slowing-down-when-loading-a-large-amount-of-data-in-a-spr

英文:

If you don´t need to access the callback from your Repository you can simply Inject the bean entityManager and detatch from your Hibernate Context.

private final EntityManager entityManager;

public void someMethod(List&lt;SomeObject&gt; objects) {
    objects.forEach(someObject-&gt; {
        res = someRepository.save(someObject);
        entityManager.detatch(res); // or use &#180;entityManager.clear();&#180; 
    });
}

This might also be useful 使用Spring Data JPA在大量实体上高效执行批量更新

https://stackoverflow.com/questions/75852833/why-is-jpa-hibernate-slowing-down-when-loading-a-large-amount-of-data-in-a-spr

huangapple
  • 本文由 发表于 2023年4月11日 02:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定