Video in progress
Why does this code fail with a unique constraint error, even though the old row was deleted first?
@Transactional
public void replacePhone(Long userId, String phone) {
Contact old = contactRepo.findByUserIdAndType(userId, "MAIN").orElseThrow();
contactRepo.delete(old);
contactRepo.save(new Contact(userId, "MAIN", phone));
// unique (user_id, type)
}
At flush time Hibernate sends SQL in its own order, not the order you called things in: INSERTs first, then UPDATEs, and DELETEs at the very end. The new row is added before the old row is gone, and the unique index is violated.
📖 Answer
In the code the order is "delete, then insert". But delete() and save() don't send SQL right away: they go into Hibernate's action queue. On flush the queue is executed roughly in this order:
- orphan removal
- INSERT
- UPDATE
- collection changes
- DELETE
This order was chosen to be friendly to FKs (the parent is added first, the child deleted later), but it doesn't know about unique constraints. The result:
insert into contact (user_id, type, phone) values (?, 'MAIN', ?) -- error!
delete from contact where id = ?
Ways to fix it:
contactRepo.delete(old);
contactRepo.flush(); // the DELETE goes out now
contactRepo.save(new Contact(userId, "MAIN", phone));
Or, and I think this is better, update the existing row instead of deleting and adding:
old.setPhone(phone);
One UPDATE, no constraint problem, and the audit history stays clean too.
The same trap exists with collections: if you remove an element with orphanRemoval and add a new one with the same key in its place, you hit the ordering problem again. On PostgreSQL you can also make the constraint deferrable initially deferred, but that bends the database to the ORM's habits, so I treat it as the last option.
Sign up to mark studied questions and save your progress.