I have a requirement in my application where before updating a record in db I want to be sure that record isn't updated by another user. I know how to implement optimistic locking by having a version identifier in the entity and that will take care of it.
@Transactional
public void updateProductApprover(Long productId, String currentLoggedInUser) {
Product product = productRepository.findById(productId)
.orElseThrow(() -> new EntityNotFoundException("Product not found"));
// if updation done by another user, then save will automatically throw exception
product.setApprovedBy(currentLoggedInUser);
productRepository.save(product);
}
So in above scenerion after product is fetched if any updation happens in product data in db, save will get failed with OptimisticLockException and that's fine.
What if view product UI page is opened on my screen and I take 2-3 min time to send update request and meanwhile another user updates something.How it's going to work ?
My assumption is that while loading the view product page, I have to load the identifier as well and send that in the update request. In the backend I have to match that with the db row version. If it's doesn't match I will ask user to refresh product page and send the update request again.
So it will be mostly a compination of :
- Explicitly implemented by my App by sending version in update request from UI page and validation against db as request will only be sending id to update and there's no way it will check for version implicitly before updation.
- Implicitly implemented by JPA when my updation happened after updateProductPrice start getting executed and product fetched from db.
Please suggest If I am missing something.
Regards,