简体   繁体   English

在休眠状态下仅更新对象的非null字段

[英]Update only non null fields of an object in hibernate

I have a use case where I have only few updated fields of a persistent object which includes the primary key of the table. 我有一个用例,其中只有几个持久性对象的更新字段,其中包括表的主键。 In this case I want to update the row with these fields only. 在这种情况下,我只想使用这些字段来更新行。 I found that hibernate doesn't provide any solution for this out of the box so I wrote a method myself that uses reflections to determine all non null fields of an object and creates an update query based on this and eventually executes it. 我发现hibernate并没有为此提供任何解决方案,所以我自己编写了一种方法,该方法使用反射来确定对象的所有非null字段,并基于此创建更新查询并最终执行它。 My application is written using spring framework. 我的应用程序是使用spring框架编写的。 As of now, the way I have done it is, I have a separate util class having an update method which takes a session object, primary key, primary key value and tablename. 到目前为止,我的工作方式是,有一个单独的util类,该类具有一个update方法,该方法接受一个会话对象,主键,主键值和表名。 Is this a good way of implementing this use case? 这是实现此用例的好方法吗? Any suggestions on making this better? 有什么更好的建议吗?

Your question is not clear to me. 我不清楚您的问题。 For update either u can do a select and then save it. 要进行更新,您可以选择一个选项然后保存。 Or just create that entity and save it (Primary key is mandatory here). 或仅创建该实体并保存它(在此必须使用主键)。 Since you want to update, you can use the first approach. 由于要更新,因此可以使用第一种方法。 No need to bother about mandatory fields here. 无需在此处烦恼必填字段。

One of the reason most of the time, that results in saving the default values in nullable field of a entity to be persisted is, because of using primitive datatype's in POJO of the entity. 大多数情况下,导致将默认值保存在要保留的实体的可空字段中的原因之一是,因为在实体的POJO中使用了原始数据类型。
Kindly check whether you are not using any primitive's. 请检查您是否未使用任何原语。 If yes switch to respective wrapper class and then save. 如果是,则切换到各自的包装器类,然后保存。 It should pass null to database on commit after save or update. 保存或更新后,应在提交时将null传递给数据库。
Hope this solves your problem :) 希望这能解决您的问题:)

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

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