Video in progress
When you assign the id yourself (a UUID or an external code), why does Spring Data `save()` send a SELECT before every INSERT?
@Entity
public class Device {
@Id
private UUID id; // generated by the client
private String model;
}
for (DeviceDto d : batch) {
deviceRepository.save(new Device(d.id(), d.model()));
}
save() decides whether an entity is new by checking whether the id is null. If the id was assigned by hand, the entity is considered "existing", so merge() is called instead of persist(), and merge first looks for the row in the database.
📖 Answer
In the SQL log, for each device:
select ... from device where id = ?
insert into device (model, id) values (?, ?)
10,000 records mean 20,000 queries, and the SELECTs aren't batched. On top of that, merge() creates a new managed copy, so your new Device(...) object stays detached.
The logic of Spring Data's SimpleJpaRepository.save():
if (entityInformation.isNew(entity)) em.persist(entity);
else return em.merge(entity);
By default isNew checks: if there's a @Version field, whether it is null; otherwise, whether the id is null (or 0 if it's a primitive).
Fixes:
1. Add @Version (as a wrapper type). On a new object the version is null, so Spring treats it as new. As a bonus you get optimistic locking.
2. Implement Persistable:
@Entity
public class Device implements Persistable<UUID> {
@Id private UUID id;
@Transient
private boolean isNew = true;
@Override public boolean isNew() { return isNew; }
@PostLoad @PostPersist
void markNotNew() { this.isNew = false; }
}
3. Call EntityManager.persist() directly, through a custom repository method.
One thing to remember: if a row with that id really exists in the database, persist() gives a duplicate key error, while merge() would have quietly updated it. So this change removes the "upsert" semantics. Check that your business logic didn't depend on that.
Sign up to mark studied questions and save your progress.