Spring data : CrudRepository’s save method and update

I wanted to know if the {save} method in CrudRepository do an update
if it finds already the entry in the database

The Spring documentation about it is not precise :

Saves a given entity. Use the returned instance for further operations
as the save operation might have changed the entity instance
completely.

But as the CrudRepository interface doesn’t propose another method with an explicit naming for updating an entity, we may suppose that yes since CRUD is expected to do all CRUD operations (CREATE, READ, UPDATE, DELETE).

This supposition is confirmed by the implementation of the SimpleJpaRepository
class which is the default implementation of CrudRepository which shows that both cases are handled by the method :

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

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

So if I call that method on an already registered entry, it’ll update
it if it finds a changed attribute?

It will do a merge operation in this case. So all fields are updated according to how the merging cascade and read-only option are set.

Leave a Comment

tech