简体   繁体   中英

How to handle version of Spring JPA in Service Layer

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

What you are trying to implement is called optimistic locking. There are two different ways how to ensure that the entity will be access or modified by only one resource at the time, optimistic and pessimistic locking.

These are bit more advanced topics so I would recommend you further reading before you make a decision which one is more suitable for your application (but rule of thumb is to use optimistic locking when you don't expect many collisions). See this tutorial or Spring Data excellent documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM