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:
- Use the object that
save()returns. In themergecase it can be a different object. - For an entity where you assign the id yourself (for example, you create a UUID in the constructor),
isNewreturnsfalse. Thensavedoes amergeand first sends an extra SELECT. You fix this with thePersistable<ID>interface and your ownisNew(). - For a managed entity you don't need to call
save(): dirty checking works anyway. - After
save()the SQL isn't sent right away (except with IDENTITY). If you need it immediately, usesaveAndFlush().
save() is itself @Transactional, so if you call it without an outer transaction, each call runs in its own transaction.
Sign up to mark studied questions and save your progress.