How can I prevent insert and allow only update of

2019-08-24 14:32发布

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).

I have tried a code as follows

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

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)

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

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)

2条回答
forever°为你锁心
2楼-- · 2019-08-24 14:41

I supose you set Id to 0 when the object does not exist in your DB so if it´s and updated object it should have an Id != 0

public void update() throws UpdateFailedException{


   if(object.getId() != 0){

          repo.save(object); // saving it, internally it will be updating.
   }else{

         throw new UpdateFailedException("Object not present to update");
        }
 }
查看更多
仙女界的扛把子
3楼-- · 2019-08-24 15:01

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.


Hibernate 4+

@DynamicInsert(true)
@DynamicUpdate(true)

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

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.

查看更多
登录 后发表回答