简体   繁体   English

Spring boot JPA批量插入异常处理

[英]Spring boot JPA batch inserts Exception Handling

I am working on a real time use case that needs to load batch of messages into SQL server table with spring boot JPA adding all the model objects to the list and doing this for batch loads repository.saveAll(list) .我正在研究一个实时用例,需要使用 spring boot JPA 将批量消息加载到 SQL 服务器表中,将所有模型对象添加到列表中,并为批量加载repository.saveAll(list)执行此操作。 Due to performance, I cannot do record by record inserts.由于性能原因,我无法通过记录插入进行记录。 I am looking for below option.我正在寻找以下选项。

Is there any way I can read the error causing message and continue with other records to insert into table.有什么方法可以读取导致错误的消息并继续将其他记录插入表中。 I have to store this error message somewhere and shouldn't pass to Downstream applications.我必须将此错误消息存储在某处,并且不应传递给下游应用程序。

The saveAll method, of Spring data JPA, is actually saving the list of records one by one: Spring数据JPA的saveAll方法,其实就是把记录列表一一保存:

/*
 * (non-Javadoc)
 * @see org.springframework.data.jpa.repository.JpaRepository#save(java.lang.Iterable)
 */
@Transactional
@Override
public <S extends T> List<S> saveAll(Iterable<S> entities) {

    Assert.notNull(entities, "Entities must not be null!");

    List<S> result = new ArrayList<S>();

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}

Still, the difference between handling the loop of messages yourself or let it to Spring data JPA to do the job: saveAll uses the property spring.jpa.properties.hibernate.jdbc.batch_size=4 to determine if batching is activated or not, and depending on the size of the batch, the insert can perform better.仍然,自己处理消息循环或让它交给 Spring 数据 JPA 来完成工作之间的区别: saveAll使用属性spring.jpa.properties.hibernate.jdbc.batch_size=4来确定批处理是否被激活,以及根据批次的大小,插入可以表现得更好。

I think you just need to loop on the messages yourself and catching the errors youself:我认为您只需要自己循环消息并自己捕获错误:

for(EnitityType entity: list){
  try{
    repository.save(entity);
  } catch (Exception e){
    // Do what you want
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM