Delly Fofie
Delly Fofie

Reputation: 314

Exception thrown by CrudRepository saveAll method if constraint is violated

I'm using spring data JPA to persist my data into the database. The CRUDRepository has the saveAll(Iterable) method that I'm using.

Since I have a unique constraint on an entity field, I'm wondering what would happen if I try to save an Interable that contains an Object which is violating this constraint.

Upvotes: 1

Views: 7224

Answers (1)

LppEdd
LppEdd

Reputation: 21134

Using the standard saveAll method, from SimpleJpaRepository, you're basically invoking multiple times, once per instance, the save method

@Transactional
public <S extends T> List<S> saveAll(Iterable<S> entities) {
    // ... Omitted

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}

@Transactional
public <S extends T> S save(S entity) {
    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

You can see an EntityManager instance is used, invoking persist or merge.
That means its rules apply, and you'll receive a ConstraintViolationException.

Upvotes: 6

Related Questions