我正在学习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()
的SELECT
和entityManager.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");
}
}