java - 如何在服务层处理Spring JPA的版本

标签 java spring hibernate spring-mvc jpa

我正在编写一个工作流程 Spring Boot Web 应用程序,其中两个人可以读取相同的数据并更新它。我想使用 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.

目前,我已在 Spring JPA 中使用 @Version 注释标记了 version 列。但我不知道如何在更新时使用它。

以下是我的代码。

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);
 }

}

任何人都可以帮助我使用任何可以使用的 Spring API。考虑到有一个 @Version 列。任何帮助,将不胜感激。谢谢

最佳答案

您尝试实现的称为乐观锁定。有两种不同的方法来确保实体一次只能被一种资源访问或修改,即乐观锁定和悲观锁定。

这些是更高级的主题,因此我建议您在决定哪一个更适合您的应用程序之前进一步阅读(但经验法则是当您预计不会发生很多冲突时使用乐观锁定)。看这个tutorial或者Spring Data优秀documentation .

关于java - 如何在服务层处理Spring JPA的版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39667376/

相关文章:

java 将 HSSFCell 转换为数字

java - 如何测试 Spring 服务 bean 本身具有 Autowiring 依赖项?

java - Spring MVC 请求映射类级别

java - DAO 管理交易的设计是否糟糕?

java - sql 格式 'YYYY-MM-DD HH24:MI:SS.FF' 到 java 的日期格式问题

java - 如何在 Java 中比较字符串?

java - Spring Data Query 抛出异常,但我无法修复它

java - spring hibernate实现一对一关系

java - hibernate查询在java spring中不起作用

java - 使用 FlowLayout 将 JPanel 添加到 JFrame