我可以在 JpaRepository 的 saveAll 中混合更新和插入吗

Jaf*_*Ali 5 java spring hibernate jpa spring-data-jpa

我使用 Spring Boot 和 Spring Data JPA 以及 Hibernate 作为持久性提供程序。我已经RepositoryJPARepository. 我有一个表的实体 Bean 列表。其中一些已经存在,而另一些则不存在。

我想知道当我saveAll从我的服务层调用并传递它时会发生什么List

Mac*_*ski 10

如果您查看SimpleJpaRepositorywhich 是 的常见实现,CrudRepository您会发现它只会为每个元素调用 save :

@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;
}
Run Code Online (Sandbox Code Playgroud)

保存本身区分自己是 topersist还是merge给定的实体:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以要回答你的问题..是的,你可以在通行证列表中混合新的和现有的实体。