如何防止插入并仅允许使用spring-boot更新对象? [英] How can I prevent insert and allow only update of my object using spring-boot?

查看:78
本文介绍了如何防止插入并仅允许使用spring-boot更新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 save()将插入我的对象(如果它不存在于db中),并且将进行更新(如果它已经存在)(使用主键字段标识的对象).

I know that save() will insert my object if its not already present in db and will go for update if its already present (object identified using the primary key field).

我尝试了如下代码

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

上面的代码无法满足我的效率要求,因为它多次轮询数据库,并且由于它不在同一事务边界中发生,所以我不能保证其行为的一致性.(即即使我得到了记录db中已经存在,因此有可能在调用保存之前从外部边界删除我的记录,因此我的保存将执行我想防止的插入操作)

The above code will not meet my efficiency requirements as its polling my db a number of times and further I cannot guarantee the consistency in its behavior since its not happening in the same transaction boundary.(ie even if I get that the record already exists in db, there is a possibility for my record to be removed from external boundary before calling the save and as a result my save will do an insert which I want to prevent)

什么是有效的方法?我还需要管理spring数据JPA的事务.

What will be an efficient way to do this ? I also need to manage the transaction for the spring data JPA.

是否可以通过任何方式知道save()是否在执行插入操作? (这样我就可以防止调用save()进行插入操作)

or Is there any way by which I can know if the save() is doing an insert or not ? (so that I can prevent calling save() if its going to do an insert)

推荐答案

假设您有10个属性,而用户仅更改了一个属性,因此可以使用@DynamicUpdate而不是更新所有10个属性.这只会更新更改的字段.

Let's say you have 10 properties and the user has just changed one property so instead of updating all the 10 properties you can use @DynamicUpdate. This will only update the changed fields.

休眠4 +

@DynamicInsert(true)
@DynamicUpdate(true)


@Entity
@Table(name = "User")
@org.hibernate.annotations.Entity(dynamicUpdate = true) //may be deprecated
public class User 


@DynamicUpdate用于指定应生成UPDATE SQL语句.whenever an entity is modified.默认情况下,Hibernate使用cached UPDATE语句设置所有表列.当使用@DynamicUpdate批注对实体进行批注时,PreparedStatement将转到include only values已为changed的列.


The @DynamicUpdate is used to specify that the UPDATE SQL statement should be generated whenever an entity is modified. By default, Hibernate uses a cached UPDATE statement that sets all table columns. When the entity is annotated with the @DynamicUpdate annotation, the PreparedStatement is going to include only the columns whose values have been changed.

这篇关于如何防止插入并仅允许使用spring-boot更新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆