Scrivio Interview library
InternalsFoundations7 min read · updated 12 November 2026

How does SimpleJpaRepository.save() decide between persist and merge, and why can saving an entity with an assigned id cause an extra SELECT?

SimpleJpaRepository.save() asks entityInformation.isNew(entity): if the entity is new it calls persist, otherwise it calls merge. By default an entity counts as new when its id is null (or zero for a primitive id), or, if it has a @Version attribute, when the version is null; so an entity whose id the application assigns looks existing, and merge first runs a SELECT to find the row. Implementing Persistable with our own isNew(), or adding a @Version field, lets Spring Data recognise new entities and skip that SELECT.

Why this question is asked

Teams that switch from database-generated ids to ids they assign themselves, such as UUIDs or order numbers from another system, often notice that every insert now costs two statements: a select and then an insert. On a batch import of a million rows, that doubles the work. Interviewers ask this to see whether we know what save() really does, since it is not a plain insert, and whether we can fix the extra query without guessing. In this answer, we will recap persist and merge, look at how save() chooses between them, reproduce the extra SELECT, fix it in two ways, and note why we should always use the object that save() returns.

1A Quick Recap of persist and merge

JPA gives us two ways to hand an entity to the EntityManager, the object that tracks entities and talks to the database. persist(entity) says: this is a new entity, start managing this exact object and insert it when we flush. It returns nothing, because the object we passed becomes the managed one.

merge(entity) says: here is an entity that may already exist, copy its state onto the managed version. To do that, the EntityManager needs the managed version. If it is not already in the persistence context, the set of entities loaded in the current transaction, Hibernate selects the row by id. If the row exists, it copies our fields onto the loaded entity and later updates it. If it does not exist, it creates a new managed entity, copies the fields and later inserts it. Either way, merge returns the managed object, which is a different instance from the one we passed in.

2How save() Decides

Spring Data's save() hides this choice from us. Its implementation in SimpleJpaRepository is short: it asks an EntityInformation object whether the entity is new, then calls persist or merge.

Java
// Simplified from SimpleJpaRepository
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
entityManager.persist(entity);
return entity; // the same object, now managed
}
return entityManager.merge(entity); // a managed copy, maybe a different object
}
Step throughHow save() picks persist or merge
  1. Does the entity implement Persistable?
    YesUse its isNew()NoUse the default rules
  2. Has a @Version field of wrapper type?
    YesNew if version is nullNoCheck the id
  3. Is the id null (or 0 for a primitive)?
    Yespersist: one INSERTNomerge: SELECT, then INSERT or UPDATE

3 steps in order. Play them, or step through them one at a time.

The decision is made from the object alone, never by asking the database.

The default isNew() rule is the key. If the entity has a @Version attribute of a wrapper type such as Long or Integer, the entity is new when the version is null. Otherwise, it looks at the id: a null id for a wrapper type, or zero for a primitive id type such as long, means new. Any other id means not new. Notice that the rule never asks the database. It only looks at the object.

3Reproducing the Extra SELECT

Now imagine an entity whose id we assign ourselves, for example a UUID created in Java before saving.

Java
@Entity
class Payment {
@Id UUID id; // assigned by the application
BigDecimal amount;
}
Payment p = new Payment();
p.id = UUID.randomUUID();
p.amount = new BigDecimal("25.00");
paymentRepository.save(p);
// SQL in the log:
// select p.id, p.amount from payment p where p.id = ? <- merge looks for the row
// insert into payment (amount, id) values (?, ?)

The id is not null, so isNew() returns false, and save() calls merge. Merge has to find out whether a payment with this id already exists, so Hibernate runs the select. It finds nothing, creates a new managed entity and inserts it. The result is correct, but every new payment costs one extra round trip to the database. In a loop of 100,000 inserts, that is 100,000 wasted selects, and it also defeats JDBC batching, because the selects interleave with the inserts.

4Fix 1: Implement Persistable

Persistable<ID> is a Spring Data interface with two methods, getId() and isNew(). If our entity implements it, Spring Data uses our isNew() instead of guessing. A common pattern is a transient flag that starts as true and is switched off once the entity has been saved or loaded.

Java
@Entity
class Payment implements Persistable<UUID> {
@Id UUID id;
BigDecimal amount;
@Transient private boolean isNew = true;
@Override public UUID getId() { return id; }
@Override public boolean isNew() { return isNew; }
@PostPersist @PostLoad
void markNotNew() { this.isNew = false; }
}
paymentRepository.save(p);
// insert into payment (amount, id) values (?, ?) <- one statement, no select

The @PostLoad callback matters. Entities loaded from the database must report isNew() as false, or saving a changed entity would call persist and fail with a duplicate key. The @PostPersist callback makes a second save() of the same object a merge rather than a second persist.

5Fix 2: Use a @Version Field

A version field gives us optimistic locking, Hibernate checks that the row has not changed since we read it, and it also gives Spring Data a reliable newness signal. A new object has a null version; once persisted, Hibernate sets it to 0 and increments it on every update.

Java
@Entity
class Payment {
@Id UUID id;
@Version Long version; // null until first persisted
BigDecimal amount;
}
paymentRepository.save(p); // version is null -> persist
// insert into payment (amount, version, id) values (?, 0, ?)

This is often the nicer fix, because most entities that are updated concurrently should have a version field anyway. It must be a wrapper type such as Long, not a primitive long, because a primitive cannot be null.

6Always Use the Returned Instance

The last point is easy to miss. When save() calls merge, the object it returns is the managed entity, and our original object stays detached, which means the persistence context does not track it. Changes we make to the original after save() are not saved, and fields that Hibernate filled in, such as the version, appear only on the returned object.

Java
Payment saved = paymentRepository.save(detached); // merge path
saved == detached; // false
detached.amount = BigDecimal.TEN; // not tracked, lost at commit
saved.amount = BigDecimal.TEN; // tracked, updated at commit

So the safe habit is to write p = repository.save(p) and continue with the returned value, whichever path save() took.

7Follow-up questions

Does the extra SELECT happen with @GeneratedValue ids?

No. With a generated id, a new entity has a null id, so isNew() returns true and save() calls persist directly. The extra select only appears when the id is set before saving and nothing else tells Spring Data that the entity is new.

Could we just call entityManager.persist ourselves?

Yes, through a custom repository fragment or an injected EntityManager, and some teams do that for bulk imports. But it spreads two ways of saving across the code. Persistable or @Version keeps save() correct everywhere, so I prefer those.

What happens if isNew() wrongly returns true for an existing row?

save() calls persist, Hibernate tries to insert, and the database rejects it with a unique constraint violation on the primary key, usually wrapped as a DataIntegrityViolationException at commit or flush. That is why the @PostLoad callback in the Persistable pattern is essential.

8Conclusion

In this answer, we saw that save() is not an insert: it asks isNew() and then calls persist or merge. The default rule looks at a @Version attribute or at the id, so an application-assigned id makes a new entity look existing, and merge runs a SELECT to find it. Implementing Persistable with a transient flag, or adding a wrapper-typed @Version field, gives Spring Data a correct answer and removes the extra query, and in every case we should continue with the instance save() returns.

What to say in the interviewAbout 100 seconds aloud

Open with

SimpleJpaRepository.save() asks the entity information whether the entity is new. If it is, it calls persist and returns the same object. If not, it calls merge and returns the managed copy.

Then, if they want more

The default newness rule only looks at the object: if there is a @Version field of a wrapper type, the entity is new when the version is null; otherwise it is new when the id is null, or zero for a primitive.

So when the application assigns the id itself, say a UUID created before saving, the id is not null, Spring Data thinks the entity already exists and calls merge. Merge has to check whether the row is there, so Hibernate runs a select by id, finds nothing, and then inserts.

That is one extra round trip per insert, which hurts in batch imports and also gets in the way of JDBC batching. There are two clean fixes.

One is to implement Persistable, return my own isNew(), and back it with a transient flag that starts true and is set to false in @PostPersist and @PostLoad, so loaded entities still count as existing.

The other is to add a @Version field as a Long; it is null for new objects, so save() persists, and I get optimistic locking as a bonus. And whichever path runs, I always continue with the object save() returns, because after a merge the original object is detached and changes to it are lost.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does SimpleJpaRepository.save() decide between persist and merge, and why can saving...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/d1646f9783/