I am writing a workflow Spring Boot Web Application where two people can read the same data and update it. I wand to handle write-write conflict using Spring JPA.
For an example, initial value of price=1000; User A and B read price from database. Now user B updates value of price to price=1500. After few second, User A updates price to price=2000 - This should throw an Exception because User A is trying to write(update) the already updated value by User B.
Currently I have marked column version
with @Version
annotation in Spring JPA. But I am not getting how to use it while updating.
Following is my code.
Entity Class
@Entity
class Product{
@Version
private int version;
private String productName;
private double price;
/* Getters and Setters */
}
Spring JPA DAO
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
Service Class
public class ProductService{
@Autowired
ProductRepository productRepo;
@Transactional
public void updateProductPrice(int id,double price){
Product p=productRepo.findOne(id);
p.setPrice(price)
// This is where price is being updated and write-write conflict needs to be handled.
productRepo.save(p);
}
}
Could anyone help me with any Spring API that can be used. Considering there is a @Version
column. Any help would be appreciated. Thanks