Protobuf 3 java: How to diff and update only those fields that are in input object? Scenario: e.g persistence to db

1.5k views Asked by At

In the below code, the api gets a "Person" obj in POST body,

My technical requirement:

  • If only one field of Person is sent, only that field must be compared to object from db.
  • if there is a change, then call save() if not just return object from db.
  • How to change the code below to be more generic and CLEAN. Any utility methods that is object type independent?
    public Model.Person save(Model.Person in) {
        String updateId = in.getId();
        System.out.println("updateId = " + updateId);
        Model.Person pExisting = get(updateId);
        Model.Person.Builder outBuild = Model.Person.newBuilder(pExisting);
        boolean hasChange = false;
        //Change only fields that are provided in POST body.
        //TODO do not compare createTs, updateTs -- they are not provided in POST to update.
        if(!in.getFirstName().isEmpty()){ //TODO - Find if there is a generic util in protobuf java.
            if(!Objects.equals(in.getFirstName(), pExisting.getFirstName())){
                outBuild.setFirstName(in.getFirstName());
                hasChange = true;
            }
        }
        if(!in.getLastName().isEmpty()){
            if(!Objects.equals(in.getLastName(), pExisting.getLastName())){
                outBuild.setLastName(in.getLastName());
                hasChange = true;
            }
        }
        
        if(!hasChange){
            System.out.println("Nothing to update ... "+System.currentTimeMillis() );
            return pExisting;
        }
        final Model.Person updatePerson = outBuild.build();
        map.put(updateId,updatePerson); //TODO move to H2 or postgres later
        return updatePerson;
    }

Sample model

syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
package my.model;

option java_outer_classname = "Model"; //muni.api.Model
option java_generic_services = false; //default, prevents complex generic
option java_multiple_files = false; //default behavior

message Person{
  //Output only
  string id=3;
  string firstName = 4;
  string lastName= 5;
  ContactChannels contactChannels = 8;
  //Output only
  google.protobuf.Timestamp createTime = 1;
  //Output only
  google.protobuf.Timestamp updateTime = 2;
}

enter image description here

0

There are 0 answers