springmongodbspring-datadbrefspring-mongodb

Spring application design when using two-way referencing in Mongo


I have two classes Person and Tasks. It's one-to-many relationship: a Person has a list of Tasks and a Task belongs to a Person.

My application has two views. In one of them I need to show the Persons and the Tasks associate to each Person. In the other one I need to show the Tasks and the Person associated with.

My first thought was use two-way referencing in Mongo. So a Person would have a list of Tasks Ids and a Task would have a Person Id.

Like this:

{
_id: ObjectID("AAF1"),
name: "Person Name",
tasks [
      ObjectID("ADF9"), 
      ObjectID("AE02"),
      ObjectID("AE73") 
    ]
}

And:

{
  _id: ObjectID("ADF9"), 
  description: "Task One",
  owner: ObjectID("AAF1")
}

But I can't figure out how I could design my Spring application to find all Persons and build a single json with a List of Tasks embedded in it to send to UI. I'm using MongoOperations so to find all Persons I use findAll(Person.class). Since I don't have the Tasks documents embedded in Persons, these objects only have the list of the Tasks Ids. The same is valid when fetching Tasks: I want to add Person to the JSON I will send to UI.

I tried to use @DBref and added a list of Tasks to Person and Person to Tasks, but this ended with a stackoverflow since each Tasks has a Person and a Person has Tasks and each Tasks has a Person and so on.


Solution

  • I just solved my problem using @JsonManagedReference and @JsonBackReference.

    class Person {
      @DBRef
      @JsonManagedReference
      private List<Tasks> tasks;
    }
    
    class Tasks {
      @DBRef
      @JsonBackReference
      private Person person;
    }