Spring Mongo DB @DBREF

This is my MongoDb structure,

db.user.find();

      

user:

{
"name" : "KSK", 
 "claim"  : [objectId("52ffc4a5d85242602e000000"),objectId("52ffc4a5d85242602e000001")] 
}

      

:

[
   {
     "_id" : "52ffc4a5d85242602e000001",
     "claimName" :"XXXX"
   },
   {
     "_id" : "52ffc4a5d85242602e000000",
     "claimName" :"YYY"
   }
]

      

My Entity class:

@Document(collection="user")
public  class User{
  @Id      
  private String id;
  private String name; 
  @DBRef
private List<Claim> claim; 
// setter and getter 

}

      

Claim class:

@Document(collection="Claim")
public class Claim{
   @Id 
   private String id; 
   private String claimName;   
}

      

I have a way to get users by name like below,

public User findByName(String name);

      

If I try to hit this method, I get an error,

No converter found capable of converting it from org.bson.types.ObjectId to java.lang.String input

So, I changed my user entity class as shown below,

Instead of private List<Claim> claim

;

Changed as Private List<ObjectId> claim

;

Now, if I execute the (findByName) method, I get a user object that has both claim object IDs ("52ffc4a5d85242602e000001", "52ffc4a5d85242602e000000"), then iterate over the list of claims and get the claim information corresponding to the claim object ID.

Instead, when I execute the findByName method, I want to get the user and claim information. How can I achieve this functionality

+3


source to share


2 answers


If you are referencing yours Claim

in a class User

with @DBRef, your JSON should not only contain an ID, but a collection reference where the ID can also be found:

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

      



This is how Spring-Data maps your Java objects to MongoDB. If you start with an empty database and let Spring create and save relationships, you should have no problem using

 @DBRef List<Claim> claims;

      

+1


source


My suggestion is not to set the Claim class in a separate @Document file, or just fall back to relational databases because this is not a Mongolian approach. Also, if you insist on the current architecture, you can try using @DBRef on this list in User.class like this:



public class ParentModel {

    @Id
    private String id;

    private String name;

    private ParentType parentType;

    private SubType subType;

    @DBRef
    private List<Model> models;

....
}

      

+1


source







All Articles