简体   繁体   中英

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. My application is written using spring framework. 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. 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.
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.
Hope this solves your problem :)

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