In hibernate, if dynamic-update is enabled, while updating the object it generates query for only modified columns
Consider a class with composite-id using components. Composite-id saveOrupdate the object. If the given key is not is DB, it adds otherwise updates the object
Now what I want is how can I merge this 2 features? For example I have a class with 3 attributes age, salary, address and a composite key id and name.
For key "1-Mohan" I already have entries for age =22, salary =30000, address =XXX. Now I want to only update its salary to 40000. When I create a new instance with the key "1-mohan" and setting only salary = 4000 and persists. Now the record fill null values for age and address since dynamic-update only happens for object fetched from DB.
Is any way there to retain its existing values unchanged and update only the given attribute without fetching the object from DB??
Setting
dynamic-updatetotruewill not setnullvalues for other fields, instead it will just update the fields which are modified.For example in your example the query generated by hibernate will be like:
So it is not going to set
nullvalues for other fields.Update:
Now based on your explanation in comments the issue has no relation with
dynamic-update.What you have to do is first use
Session.getto get your object based on thecomposite-id. Now your object will have all fields set. Now update thesalaryfield and then callsaveOrUpdatemethod.If the
dynamic-updateisfalsethen hibernate will generateupdatequery by including all the fields.If the
dynamic-updateistruethen hibernate will generateupdatequery by including only thesalaryfield as mentioned in my answer.