13

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.

I want to know what will happen when I call saveAll from my service layer and pass this List?

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Jafar Ali
  • 1,084
  • 3
  • 16
  • 39

1 Answers1

20

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;
}

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.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • 1
    One strange issue with this is that saveAll can’t accurately determine whether the entity is new or not. This leads to duplication of records. – saran3h Jan 24 '22 at 12:52
  • How is that possible, don't we have an `@Id` column that ensures uniqueness, and also acts as an identifier of an entity? – Prasannjeet Singh Sep 09 '22 at 12:39
  • could this at all be related to maybe the ID generation taking precedence somehow? – It Grunt Sep 26 '22 at 16:51