Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mix both update and insert in saveAll from JpaRepository

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?

like image 319
Jafar Ali Avatar asked Aug 19 '19 06:08

Jafar Ali


People also ask

Is it possible to mix new and existing entities in Saveall?

So to answer your question.. yes you can mix both new and existing entities in the passes list. 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.

What is the difference between Saveall and merge in Spring Boot?

Behind the scene, saveAll () call save (), which, in case of non-new entities (entities that have assigned IDs), will call merge (). Calling merge () instructs Hibernate (the default Spring Data persistence provider) to trigger a SELECT statement before an INSERT.

What is the difference between the save and saveorupdate events?

The save and saveOrUpdate are just aliases to update and you should not probably use them at all. Some developers call save even when the entity is already managed, but this is a mistake and triggers a redundant event since, for managed entities, the UPDATE is automatically handled at the Persistence context flush time.

How do I update and persist an entity in JPA?

To persist an entity, you should use the JPA persist method. To copy the detached entity state, merge should be preferred. The update method is useful for batch processing tasks only. The save and saveOrUpdate are just aliases to update and you should not probably use them at all.


1 Answers

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.

like image 190
Maciej Kowalski Avatar answered Nov 14 '22 09:11

Maciej Kowalski