英文:
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();'
});
}
这可能也会有帮助
英文:
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<SomeObject> objects) {
objects.forEach(someObject-> {
res = someRepository.save(someObject);
entityManager.detatch(res); // or use ´entityManager.clear();´
});
}
This might also be useful
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论