问题描述
我知道对此参数有很多类似的问题,但是我确实需要一个可行的解决方案。
I know that there are many similar questions about this argument, but I really need a working solution.
我正在尝试配置Spring Boot和Spring Data JPA为了批量批量插入。
I'm trying to configure Spring Boot and Spring Data JPA in order to make bulk insert in a batch.
目标是:提交每条N记录,而不是制作<$时的每条记录c $ c> repository.save()操作。
The target is: commit each N-records, not every single record when making repository.save()
action.
我从现在开始在应用程序中尝试过的内容。属性
:
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.generate_statistics=true
但没有成功。我已经监视了数据库,并且记录是一张一张地保存在表中,而不是像我配置的那样一张白一张地保存在100张中。
But with no success. I've monitored the database and records are persisted in tables one-by-one, not 100-by-100 like I've configured.
UPDATE
这里是实现:
@Component
public class BulkInsert {
@Autowired
MyRepository repository;
public void process() {
PodamFactory podamFactory = new PodamFactoryImpl();
for(int i=0;i<10000;i++) {
MyEntity myEntity = podamFactory.manufacturePojo(MyEntity.class);
repository.save(myEntity);
}
}
}
实体:
@Entity
@Table(name="MYTABLE")
@NamedQuery(name="MyEntity.findAll", query="SELECT m FROM MyEntity m")
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name="DESCRIPTION")
private String description;
@Id
@Column(name="ID")
private String id;
public MyEntity() {
}
// getters and setters
}
存储库:
public interface MyRepository extends CrudRepository<MyEntity, String> {
}
推荐答案
尝试像这样更改代码:
public void process() {
PodamFactory podamFactory = new PodamFactoryImpl();
List<MyEntity> myEntities = new ArrayList<>(10000);
for(int i = 0; i < 10000; i++) {
myEntities.add(podamFactory.manufacturePojo(MyEntity.class));
}
repository.save(myEntities); // for Spring Boot prior 2.0
// repository.saveAll(myEntities); - for Spring Boot since 2.0
}
P.S。不要忘记打开 spring.jpa.show-sql
来查看结果
P.S. don't forget to turn on spring.jpa.show-sql
to see result
UPDATE
也请检查我有关批量插入的另一个答案:
Please also check my another answer about bulk insert:How to do bulk (multi row) inserts with JpaRepository?
这篇关于Spring Boot和Spring Data JPA的批量插入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!