Video in progress
A user keeps a form open for 10 minutes and then saves. How do you prevent a "lost update" across several HTTP requests?
I give the version to the client (a DTO field or an ETag), and it comes back with the save. The server loads the entity, compares the incoming version with the current one, and returns 409 if they don't match. I don't keep the persistence context alive between requests.
📖 Answer
Hibernate's @Version works inside a single transaction. Between two HTTP requests, the read and the write are separate transactions, so we have to carry the version ourselves.
public record ProductForm(Long id, long version, String name, BigDecimal price) {}
@Transactional
public void update(ProductForm f) {
Product p = repo.findById(f.id()).orElseThrow();
if (p.getVersion() != f.version()) {
throw new ConflictException("Ma'lumot boshqa foydalanuvchi tomonidan o'zgartirilgan");
}
p.rename(f.name());
p.changePrice(f.price());
} // at flush, "where version = ?" is checked again
There are two layers of protection: the manual comparison covers the long gap, and @Version's SQL condition covers the short gap between find and flush.
In REST you can make this standard: ETag: "7" in the GET response, If-Match: "7" in the PUT request, and 412 Precondition Failed if they don't match. Client libraries understand this.
What I avoid:
- keeping a detached entity in the session and
merge()ing it later: memory, serialization, and the problem of merge copying null fields; - not sending the version in a DTO that gets
merge()d: then Hibernate takes the version from the database, and the check is meaningless.
UX is part of the design too: on a conflict, showing the user the new values and letting them reapply their changes is much better than a "try again" message.
Sign up to mark studied questions and save your progress.