Video in progress

What actually happens inside the save() method in Spring Data JPA?

SimpleJpaRepository.save() checks whether the entity is new: if it is, it calls em.persist(), otherwise em.merge(), and returns the result. It usually decides that an entity is new from its id (or @Version) being null.

📖 Answer

A simplified view:

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

The practical consequences:

  1. Use the object that save() returns. In the merge case it can be a different object.
  2. For an entity where you assign the id yourself (for example, you create a UUID in the constructor), isNew returns false. Then save does a merge and first sends an extra SELECT. You fix this with the Persistable<ID> interface and your own isNew().
  3. For a managed entity you don't need to call save(): dirty checking works anyway.
  4. After save() the SQL isn't sent right away (except with IDENTITY). If you need it immediately, use saveAndFlush().

save() is itself @Transactional, so if you call it without an outer transaction, each call runs in its own transaction.