What is the best approach to partially update a REST Resource in JAVA using JDBC Batch Update?

Viewed 44

I have an REST put endpoint that allows the admin user to update the preference of multiple users at once. Every user is supposed to have two preferences. The admin can either update one or both the preferences for a particular user. An example json request for the same is below.

{
  "users": [
    {
      "userId": "101"
      "updateFields": {
        "preference1": "ABC"
      }
    },
    {
      "userId": "102"
      "updateFields": {
        "preference1": "ABC"
        "preference2": "DEF"
      }
    }
  ]
}

I will be using a batch update in JDBC to update the info. I need to retain the information if a preference is not mentioned. The query looks like follows.

update preferences set pref1 = ?, pref2 = ? where userId= ?

The question is how do I retain existing preference when only one preference is mentioned(ex user 101s update).

The only solution I have is to retrieve the existing data before update and use them to set it again but I was wondering if there is a better solution to this?

1 Answers

If it's just the two preferences, you could use three different statements, One for pref1 only, one for pref2 only, and one for both.

Once you get to three fields, that would be pretty unworkable though.

Another, probably sub-optimal solution would be to have one update statement per property, and for each Preferences object, execute one statement per property being updated.

For example, for the '101' object, you would execute one update for preference1, while for the '102' object, you would execute two separate updates, one for preference1, and one for preference2.

Related