当将 Spring Data 与 Java 8 一起使用时,我们有两个选项来保存集合:
我们可以使用经典的
List<S> save(Iterable<S> entities)
获取整个列表的方法。
示例:someOtherRepository.save( someRepository.findAll() .stream() .map(something -> { //some operations return someOtherThing; }) .collect(Collectors.toList()) );
我们可以使用
S save(S entity)
方法采用单个实体并在stream
中使用它在map
.
示例:someRepository.findAll() .stream() .map(something -> { //some operations return someOtherThing; }) .map(someOtherRepository::save) .collect(Collectors.toList());
问题是:
这两种方法的执行时间有区别吗?如果是,哪个更有效(更快)。
最佳答案
save(Iterable<S> entities)
依赖于迭代和调用 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;
}
因此,两者在性能方面应该给出相同的结果。
要进行批量插入,您必须在 hibernate 配置 ( hibernate.jdbc.batch_size
) 中指定它并自行处理刷新。
关于java - Spring Data JPA 保存方法在 Java 8 功能图中的有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45342603/