Spring Mongo DB @DBREF Spring Mongo DB @DBREF mongodb mongodb

Spring Mongo DB @DBREF


If you reference your Claims in the User class with @DBRef, your JSON should not only contain the ID but the reference to the collection where to find the ID as well, like this:

{  "name" : "KSK",   "claim" : [      {        "$ref" : "claim", // the target collection       "$id" : ObjectId("52ffc4a5d85242602e000000")     }  ] }

That is how Spring-Data maps your Java objects to MongoDB. If you start with a blank database and let Spring create and save the relations, you should have no problems using

 @DBRef List<Claim> claims;


My suggestion is not to set that Claim class into separate @Document or just switch back to Relational Databases, because it's not a Mongo approach.Also, if you insist on current architecture you can try using @DBRef above that List in User.class into smth like this:

public class ParentModel {    @Id    private String id;    private String name;    private ParentType parentType;    private SubType subType;    @DBRef    private List<Model> models;....}


as an alternative to @DBRef, take a look at RelMongo (link)which provides a powerfull way to manage relations, in your case it will be like this :

@OneToMany(fetch = FetchType.LAZY)private list<Claim> claims;