I am using Spring data jpa for persistence. Say, I have to update a model. This model has ‘n’ number of fields along with a primary Key.
{ "some_model":{ "id":"5527716", "field_one": "44248156", "field_two": "44248156", "field_three": "44248156", "field_four": "44248156", "field_five": "44248156", "field_six": "44248156", "field_seven": "44248156", "field_eight": "44248156", "field_nine":"65037768" } }
Considering above json as a representation of my model, I want to update only those fields which are incoming in the json (primary key is Id which will always be there). Is there any way I can achieve without having to check each field explicitly and setting them?
Say I get a request like:
{ "some_model":{ "id":"5527716", "field_one": "44248156", "field_two": "44248156", "field_three": "44248156", "field_eight": "44248156", "field_nine":"65037768" } }
I want to achieve update (upsert kind of thing) just using repository.save or something similar. Currently using repository’s save method internally updates the model using primaryKey value but sets the values for absent fields as null. I want those fields to remain unchanged.
Main problem is: there are hundreds of models and each model has around 10-15 fields and explicitly checking each field and updating for all the models would be a nightmare.
I also checked about @DynamicUpdate
annotation but it seems to be applicable for explicit setting where generated sql is optimized.
I would appreciate any ideas regarding this.
Advertisement
Answer
I found that the exact requirement of my question can’t be fulfilled. Dozer Bean Mapper seemed like an option but it’s more about mapping bean objects of different classes where we can correspond the fields to be mapped which is not my case.
The solution was to alter the approach wherein all the required information are sent while doing an update.
As Simon pointed out in the comment:
Simple answer: that’s not possible. Because after deserialization if fields are missing the value is null. Java is a static typed language and does not fit very well with your requirments.