Video in progress
After `merge()`, why don't changes to the object you passed as the argument reach the database?
merge() does not make the detached object managed. It copies its state onto the managed copy in the persistence context and returns that copy. Later changes must be made on the returned object.
📖 Answer
@Transactional
public void update(UserDto dto) {
User detached = mapper.toEntity(dto); // has an id, but is detached
User managed = em.merge(detached);
detached.setStatus(Status.BLOCKED); // ignored
managed.setLastSeen(Instant.now()); // this goes into the UPDATE
}
Roughly what happens inside merge(): Hibernate finds the entity by id in the persistence context or in the database (with a SELECT), copies the fields of the detached object onto it, and returns that managed object. The argument stays detached.
That's why you should always use the result:
user = em.merge(user);
save() in Spring Data works the same way: for a non-new entity it calls merge() inside, and you must work with the returned object. Throwing away the result with repository.save(user); isn't a very common mistake, but if you then keep working with that same user, this is where lost changes come from.
One more subtle point: merge() copies all the fields, including nulls. If you build an incomplete object from a DTO and merge it, you wipe out values in the database.
Sign up to mark studied questions and save your progress.