Reputation: 31
I'm using Spring boot JPARepository saveall() to insert records in batch but it fails the whole batch on encountering any exception. How can I skip the exception in batch insertion and continue saving other records?
Upvotes: 0
Views: 1245
Reputation: 121
saveAll() of SimpleJpaRepository
uses @Transactional that boosts performance of saving the batch. More details here: https://www.baeldung.com/spring-data-save-saveall
You can iterate over the entities yourself, make checking to avoid exception, and use save() to Insert or Update entities one by one.
Use @Transactional to get the same performance as saveAll()
Upvotes: 0
Reputation: 31640
There is a feature in Spring Batch that is called chunk scanning, which basically allows you to "scan" a chunk for failed items and skip them if an exception occurs while writing the whole chunk. To activate this feature, you need to use a fault-tolerant step and declare the exception as skippable.
Please check the section Configuring Skip Logic in the reference documentation for more details about that feature. You can also find a sample here.
Upvotes: 0
Reputation: 36203
You can't. You have to iterate over the list and call save
for each entry.
Btw. that's exactly what saveAll
does:
That's the implementation of SimpleJpaRepository
:
@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<>();
for (S entity : entities) {
result.add(save(entity));
}
return result;
}
Upvotes: 1