在JPA中根据对象的ID和版本删除对象



我正在学习JPA,我试图在Spring MVC web应用程序中使用它。我需要实现一个删除对象/记录的方法。目前,我有以下方法的实现:

@Transactional
public void deleteProduct(int productId, int productVersion) {
    Product product = entityManager.find(Product.class, productId);
    product.setVersion(productVersion);
    entityManager.remove(product);
}

productVersion用于乐观锁定。它是来自web GUI的对象/记录的旧版本。

此方法删除DB中的记录,但是当数据库中记录的版本与productVersion不匹配时,它不会抛出任何异常。(我只有一个问题与删除对象:当我更新记录与entityManager.merge(product),我得到一个异常的消息:Row was updated or deleted by another transaction。)

Hibernate生成以下SQL查询:delete from Product where id=? and version=?,即它尝试检查version字段。

我做错了什么?

另外,通过id删除对象是正确的方法吗?我担心我的方法生成了两个SQL查询:entityManager.find()SELECTentityManager.remove()DELETE。是否有更优化的方式来删除对象/记录?

产品类

@Entity
public class Product {
    @Id
    @GeneratedValue
    protected int id;
    protected String name;
    protected BigDecimal price;
    @Version
    protected int version;
    // getters and setters
}

一种方法是在一个查询中手动完成,如下所示:

@Transactional
public void deleteProduct(int productId, int productVersion) {
   int isSuccessful = entityManager.createQuery("delete from Product p where p.productVersion=:productVersion and p.id=:id")
            .setParameter("id", productId)
            .setParameter("productVersion", productVersion)
            .executeUpdate();
    if (isSuccessful == 0) {
        throw new OptimisticLockException(" product modified concurrently");
    }
}

最新更新