我可以在JpaRepository中将update和insert混入saveAll吗? [英] Can I mix both update and insert in saveAll from JpaRepository
问题描述
我正在使用Spring Boot和Spring Data JPA和Hibernate作为持久性提供程序.我用JPARepository
扩展了我的Repository
接口.我有一张表的实体Bean列表.其中一些已经存在,而另一些则不存在.
I am using Spring Boot and Spring Data JPA and Hibernate as the persistence provider. I have extended my Repository
interface with JPARepository
. I have a list of Entity Bean for a table. Some of them already exist and some of them not.
我想知道当我从服务层调用saveAll
并传递此List
时会发生什么情况?
I want to know what will happen when I call saveAll
from my service layer and pass this List
?
推荐答案
如果您查看SimpleJpaRepository
,它是CrudRepository
的常见实现,您会发现它只会为每个元素调用save:
If you look at the SimpleJpaRepository
which is a common implementation of the CrudRepository
you can see that it will simply invoke save for each of the elements:
@Transactional
public <S extends T> List<S> saveAll(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities not be null!");
List<S> result = new ArrayList<S>();
for (S entity : entities) {
result.add(save(entity));
}
return result;
}
保存本身可以区分给定实体persist
还是merge
:
The save itself distinguishes itself whether to persist
or merge
the given entity:
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
因此,回答您的问题.是的,您可以在通过列表中混合使用新实体和现有实体.
So to answer your question.. yes you can mix both new and existing entities in the passes list.
这篇关于我可以在JpaRepository中将update和insert混入saveAll吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!