简体   繁体   English

具有复合ID休眠的动态更新

[英]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的类。 Composite-id saveOrupdate the object. 复合ID saveOrupdate对象。 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. 例如,我有一个具有年龄,工资,地址和复合键ID和名称的3个属性的类。

For key "1-Mohan" I already have entries for age =22, salary =30000, address =XXX. 对于键“ 1-Mohan”,我已经有以下条目:年龄= 22,薪水= 30000,地址= 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. 现在,我只想将其薪水更新为40000。当我用键“ 1-mohan”创​​建一个新实例并仅设置薪水= 4000并保持不变时。 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?? 有什么方法可以保持其现有值不变并仅更新给定属性,而无需从DB中获取对象?

Setting dynamic-update to true will not set null values for other fields, instead it will just update the fields which are modified. dynamic-update设置为true不会为其他字段设置null值,而是只会更新已修改的字段。

For example in your example the query generated by hibernate will be like: 例如,在您的示例中,hibernate生成的查询将类似于:

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

So it is not going to set null values for other fields. 因此,不会为其他字段设置null值。

Update: 更新:

Now based on your explanation in comments the issue has no relation with dynamic-update . 现在,根据您在注释中的解释,该问题与dynamic-update无关。

What you have to do is first use Session.get to get your object based on the composite-id . 您要做的是首先使用Session.get根据composite-id获取对象。 Now your object will have all fields set. 现在,您的对象将设置所有字段。 Now update the salary field and then call saveOrUpdate method. 现在更新salary字段,然后调用saveOrUpdate方法。

If the dynamic-update is false then hibernate will generate update query by including all the fields. 如果dynamic-updatefalse那么hibernate将通过包含所有字段来生成update查询。

 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. 如果dynamic-updatetrue那么休眠将通过仅包含我的答案中提到的salary字段来生成update查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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