whitenexx
whitenexx

Reputation: 1370

How to reference a different domain model from within a map with spring boot correctly?

I've the following mongodb document:

{ 
    "_id" : ObjectId("57a068b13a4b500d7f2c72a2"), 
    "results" : [
        {
            "position" : NumberInt(12), 
            "product" : DBRef("product", ObjectId("579f92cfcb22890ba7b0ae15"))
        }
    ]
}

How can i map this document correctly to a spring boot domain/model class using spring-data-mongodb?

Using the following attribute in the model works but i think it's not clear enough because i've to ensure that the object in the map is an objectId or DBRef.

private List<Map<String, Object>> results;

Also creating a separate result model and using private List<Result> results; didn't work.

Upvotes: 3

Views: 655

Answers (1)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83131

Something roughly equivalent to this should do the trick:

class MyDocument {
  ObjectID id;
  List<Result> results;
  …
}

class Result {
  int position;
  @DBRef Product product;
  …
}

class Product {
  ObjectId id;
}

The important bits:

  • A dedicated type for the objects embedded in the base document.
  • A pointer to the referred-to document using @DBRef
  • The referred-to object having to use ObjectId as identifier type

Upvotes: 3

Related Questions