Java CrudRepository 和 Hibernate:交易中的 save(List<S>) 与 save(Entity)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32793403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:06:13  来源:igfitidea点击:

CrudRepository and Hibernate: save(List<S>) vs save(Entity) in transaction

javaspringhibernatejpa

提问by BPm

Would it make any difference if I do:

如果我这样做会有什么不同吗:

@Transactional
public void processData() {
    List<MyEntity> entities = ....;
    MyEntityRepository.save(entities);
}

vs.

对比

@Transactional
public void processData() {
    List<MyEntity> entities = ....;
    for (MyEntity entity : entities) {
        MyEntityRepository.save(entity);
    }
}

What is the difference in terms of the underlying queries and performance?

在底层查询和性能方面有什么区别?

采纳答案by Ori Dar

From SimpleJpaRepository:

来自SimpleJpaRepository

@Transactional
public <S extends T> List<S> More 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, your second business method only shadows save(Iterable<S> entities)Crud Repository method, in the sense that it iterates the list and calls save(S)on your behalf.

因此,您的第二个业务方法只会影响save(Iterable<S> entities)Crud Repository 方法,因为它save(S)代表您迭代列表和调用。

As long as transaction is demarcatedfrom your processDatabusiness method, there is no really a difference in performance or queries executed.

只要事务与您的processData业务方法分开,性能或执行的查询就没有真正的区别。

回答by kayochin

As what has been mentioned by Ori Dar, there is no really a difference.

正如Ori Dar所提到的,没有真正的区别。

However, there is one thing you should notice:the method used to a save a list of elements has been renamed into <S extends T> List<S> saveAll(Iterable<S> entities)in 2.2.0.M1according to the repo history, and the savemethod no longer takes as argument a list.

但是,您应该注意一件事:用于保存元素列表的方法已根据repo history<S extends T> List<S> saveAll(Iterable<S> entities)2.2.0.M1 中重命名,并且该方法不再将列表作为参数。save

Since I don't have 50 reputation to comment the answer or question above, I have to write a new answer about this change.

由于我没有 50 声望来评论上述答案或问题,因此我必须针对此更改写一个新答案。

回答by Rishabh Agarwal

For SpringData Jpa, a cleaner approach will be to use repository.saveAllinstead of a forloop with repository.save. saveAllwill automatically iterate through the list and save it.

对于SpringData JPA,一个更简洁的方法将是使用repository.saveAll,而不是for带环repository.savesaveAll将自动遍历列表并保存它。

saveAllis a part of JpaRepository, so no need to define any method.

saveAll是 JpaRepository 的一部分,所以不需要定义任何方法。