0

How can I set values into an existing object only if the incoming fields are not null? On form submission, I check to see if incoming fields are not null, before updating the existing object on a database save. I have too many fields and too many snippets for each field. Is there an elegant way to set only the updated fields on the existing object?

protected void updateFoo(Foo input, Foo existing) {
    if (input.getEducation() != null) {
        existing.setEducation(input.getEducation());
    }
    ...
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Rpj
  • 5,348
  • 16
  • 62
  • 122
  • 2
    Spring has something called `BeanUtils.copyProperties` that can be configured to skip null values. This question deals with that situation: https://stackoverflow.com/questions/19737626/how-to-ignore-null-values-using-springframework-beanutils-copyproperties – Jeroen Steenbeeke May 21 '21 at 12:58
  • @Andy intention is to reduce complexity at the updateFoo either using additional libraries or other utilities or any build time annotations. Appreciate if you can provide possible options to resolve, as the number of attributes keeps increasing all the time and it adds to more maintenance – Rpj May 21 '21 at 14:31

1 Answers1

1

You can combine all fields within a map. When any new values occur, update a sub-map and just transfer the sub-map to the receiver.

https://www.javatpoint.com/java-map

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/HashMap.html

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/SortedMap.html

Example:

your database row

Value: 1  2  3  4  5

You create one time a map out of any database row, maybe row 0 and use this map as reference card at your receiver side.

myMap

Key:   A  B  C  D  E
Value: 1  2  3  4  5

Your database changes to:

your database row

Value: 1  2  7  4  9

You create a sub-map.

mySubMap

Key:   C  E
Value: 7  9

You transfer that sub-map to the receiver and update the receiver.

There are some minor logical bugs in this text, but I hope you get the idea.

PS maps work faster than endless if...else, especially in huge databases

paladin
  • 765
  • 6
  • 13