简体   繁体   中英

Dynamic Update with composite id hibernate

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-update to true will not set null values 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:

 UPDATE USER_TABLE SET SALARY=? 
    WHERE ID=? AND NAME=?

So it is not going to set null values 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.get to get your object based on the composite-id . Now your object will have all fields set. Now update the salary field and then call saveOrUpdate method.

If the dynamic-update is false then hibernate will generate update query by including all the fields.

 UPDATE USER_TABLE SET SALARY=?, AGE=?, ADDRESS=? 
    WHERE ID=? AND NAME=?

If the dynamic-update is true then hibernate will generate update query by including only the salary field as mentioned in my answer.

 UPDATE USER_TABLE SET SALARY=? 
    WHERE ID=? AND NAME=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM