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)
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
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+
The
@DynamicUpdate
is used to specify that the UPDATE SQL statement should be generatedwhenever an entity is modified.
By default, Hibernate uses acached UPDATE
statement that sets all table columns. When the entity is annotated with the @DynamicUpdate annotation, the PreparedStatement is going toinclude only
the columns whosevalues
have beenchanged
.