Issue
When using Spring Data together with Java 8 we have two options to save the collection:
We can use classic
List<S> save(Iterable<S> entities)
method that takes the whole list.
Example:someOtherRepository.save( someRepository.findAll() .stream() .map(something -> { //some operations return someOtherThing; }) .collect(Collectors.toList()) );
We can use
S save(S entity)
method that takes single entity and use it in astream
in amap
.
Example:someRepository.findAll() .stream() .map(something -> { //some operations return someOtherThing; }) .map(someOtherRepository::save) .collect(Collectors.toList());
The question is:
Is there a difference in execution time between those two approaches? If yes which is more effective (faster).
Solution
save(Iterable<S> entities)
relies on iterating and invoking save(S entity)
:
@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {
List<S> result = new ArrayList<S>();
if (entities == null) {
return result;
}
for (S entity : entities) {
result.add(save(entity));
}
return result;
}
So the two should give the same result in terms of performance.
To do batch insert, you have to specify it in your hibernate configuration (hibernate.jdbc.batch_size
) and handle yourself the flush.
Answered By - davidxxx
Answer Checked By - David Marino (JavaFixing Volunteer)