Video in progress

Strong Junior 🌱 Spring

How does save() in Spring Data JPA tell a new object from an existing one?

SimpleJpaRepository.save first checks whether the entity is new: if the id is null (0 for primitives) — persist, otherwise — merge. If there's a @Version field, it looks at that instead.

📖 Answer

Simplified code:

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

This leads to three traps.

If you assign the id yourself (for example, generate a UUID in code), Spring thinks the object already exists and calls merge. And merge sends a SELECT first — an extra query before every insert. The fix: implement Persistable<ID> and control isNew() yourself, or add a @Version field.

Second — the object returned by merge is a different instance:

Product p = new Product(5L, "Olma");
repo.save(p);
p.setName("Nok"); // p is not managed, this change won't be saved

Always work with the value save returns: p = repo.save(p);

Third — for a managed entity you don't need save at all. If you change an object loaded with findById inside a transaction, Hibernate sends the UPDATE on commit by itself (dirty checking).