Search code examples
javajooq

Update only changed fields in JOOQ record using POJO with partial data


I have a very similar issue as the following post, but slight variation. Update only changed fields in JOOQ record using POJO

I get the same JSON object both for create and update call. In the update call, I might not receive all the fields, so I want to make sure I update only the changed fields and not replace the fields that weren't provided with null. There is no constraint on the database.

I am following the above answer, but running into an error with slight modification.

UserRecord existingRecord = existingUserRecordOptional.get();
UserRecord newUserRecord = new UserRecord();
newUserRecord.from(userPojo);

for (int i = 0; i < newRecord.size(); i++) {
   if (nonNull(newRecord.get(i)) && !Objects.equals(existingConsumerRecord.get(i), newRecord.get(i))) {
      existingUserRecord.setValue(DSL.val(existingUserRecord.field(i)), DSL.val(newUserRecord.getValue(i)));
   }
}

Error I am receiving is:

Field ('"db"."table"."description"') is not contained in Row (...)


Solution

  • Do this instead:

    existingUserRecord.setValue(
      // Don't wrap this in DSL.val()
      (Field) existingUserRecord.field(i), 
      DSL.val(newUserRecord.getValue(i))
    );
    

    DSL.val() is used to create a bind value.

    However, since you've linked to the previous question, why not just follow that approach that doesn't copy values between records? You could use the newUserRecord and unset all changed flags for the columns you don't want to send to the database.