Video in progress

Strong Middle 🐻 Hibernate and JPA

How can `merge()` of a detached entity silently wipe out another user's change?

merge() copies all the fields of the detached object over the current state in the database. If there's no @Version, any change someone else made since you opened the form is overwritten with the old values: a lost update.

📖 Answer

The scenario:

  1. 10:00: Ali opens a product card: price 100, stock 20. The object goes to the client.
  2. 10:02: the warehouse service drops the stock to 5.
  3. 10:05: Ali changes only the price to 120 and sends the whole object back.
@Transactional
public void save(ProductDto dto) {
    em.merge(mapper.toEntity(dto)); // stock = 20 came back too
}

merge() loads the current state from the database (stock = 5), writes all the fields from the DTO over it (stock = 20), and runs the UPDATE. The warehouse change is gone, and there's no error.

Two things work together against this:

@Version, and sending it to the client. If the version travels with the DTO and comes back, merge() sees the old version and throws OptimisticLockException. Important: calling setVersion() by hand on a managed entity may be ignored by Hibernate, so do the check yourself:

Product p = em.find(Product.class, dto.id());
if (!p.getVersion().equals(dto.version())) throw new ConcurrentEditException();
p.setPrice(dto.price());   // only the allowed field

Updating only the changed field, not the whole object. In the code above, stock isn't touched at all. That's PATCH semantics, and it's much safer than merge().

That's why I avoid turning a DTO that arrives from the API directly into an entity and calling merge().