How to serialize feedback in protobuf

I have the following proto file

message Person {

    // ID
    required int32 id = 1;

    // name
    required string name = 2;

    // email
    optional string email = 3;

    // tasks
    repeated Task tasks = 4;
}

message Task {
    //ID
    required int32 id = 1;

    //owner
    optional Person owner =2;

}

      

The person has a to-do list that is a one-to-many relationship. In the problem, I establish an inverse relationship to a person, which is a one-to-one relationship.

My question is how to serialize the inverse of the current person in the task when I create the task in the person object since the person object hasn't been built yet. please refer to ???? (question mark) in the following code snippet. I have the following code to serialize.

PersonMsg.Person.Builder personBuilder = PersonMsg.Person.newBuilder();  
    personBuilder.setId(1);  
    personBuilder.setName("Alex");  
    personBuilder.setEmail("alex@gmail.com");  
    personBuilder.addTasks(PersonMsg.Task.newBuilder()
                            .setId(11)
                            .setOwner("??????"));
    personBuilder.addTasks(PersonMsg.Task.newBuilder()
                            .setId(12)
                            .setOwner("???????"));
    PersonMsg.Person xxg = personBuilder.build(); 

      

Thanks in advance!

+3


source to share


2 answers


This is basically a circular dependency and you need to solve it or the program won't compile.

There is already a composition between Person

and Task

, since it Task

is a member Person

. Basically you don't need to link Task

to Person

as there is already an existing link.



If you really need a double reference, I would suggest using a post reference (like a foreign key) for the Person object.

message Task {
    //ID
    required int32 id = 1;
    //owner
    optional int32 ownerId =2; //which is the owner Person id.

}

      

+2


source


This does not work because protocol buffers do not support pointers. The field tasks

Person

does not store pointers to tasks, it stores actual tasks. The field owner

Task

does not store a pointer to the person, it keeps the full one Person

. You can't have two different ones Task

that have the same owner

, because that would require pointers.

This means that a Protobuf message is always strictly a tree. This is different from Java in general, where objects form an arbitrary graph, possibly with loops.



The solution is for the field to owner

Task

store the ID of the person rather than store the full one Person

. Then your code should know how to search Person

based on ID.

+2


source







All Articles