【发布时间】:2019-08-06 07:35:46
【问题描述】:
我知道 save() 将插入我的对象,如果它不存在于数据库中,如果它已经存在(使用主键字段标识的对象)将进行更新。
我试过如下代码
public void update() throws UpdateFailedException{
boolean b= findByPK(); // checking if the entry is already present.
if(b){
repo.save(object); // saving it, internally it will be updating.
}else{
throw new UpdateFailedException("Object not present to update");
}
}
上面的代码不能满足我的效率要求,因为它会多次轮询我的数据库,而且我不能保证其行为的一致性,因为它没有发生在同一个事务边界中。(即即使我得到了记录数据库中已经存在,在调用保存之前,我的记录有可能从外部边界中删除,因此我的保存将执行我想要阻止的插入)
什么是有效的方法?我还需要管理 Spring Data JPA 的事务。
或有什么方法可以知道save() 是否正在插入? (这样我就可以防止调用 save() 如果它要进行插入)
【问题讨论】:
-
如果对象中有 PK id,它将更新实体。您可以检查并跳过从数据库中提取数据(ID 应该存在于数据库中!)。您可以在存储库中创建仅更新方法。
-
您能详细说明一下吗?
-
I cannot guarantee the consistency in its behavior since its not happening in the same transaction boundary。这很容易解决,使用@Transactional。
标签: java spring hibernate spring-boot spring-data-jpa