0
votes

Newbie Alert !

I just installed mongodb 2 days back and started creating REST api's over spring.

So i have a collection, userinfo, where a sample document would look like

{"_id":"5c62588e5e1fbc37dc9746d3","name":{"first":"rajan","last":"rawat"},"age":32}

I created the field name as Object type in the collection.

Now creating the entity class for it in java

@Document(collection = "userinfo")
 public class UserInfo {

    @Id
    private String id;
    private Name name;
    private int age;
}

where the Class Name is

public class Name {

    private String firstName;
    private String lastName;
}

On running the API, the response I get is

{"id":"5c62588e5e1fbc37dc9746d3","name":{"firstName":null,"lastName":null},"age":32}

If I change the type in UserInfo class to string like,

@Document(collection = "userinfo")
public class UserInfo {

    @Id
    private String id;
    private String name;
    private int age;
}

The response changes to

{"id":"5c62588e5e1fbc37dc9746d3","name":"{ \"first\" : \"rajan\", \"last\" : \"rawat\" }","age":32}

which basically gives a string representation of the object from collection.

My Questions.

  1. Is there something wrong with the way I designed the collection in mongoDB. I am assuming my use case is a reason why the Object type would have been introduced.
  2. How do I map this collection in java i.e @Document. What am I missing ? Is there Something else I need to configure in the Class Name
1
set @Document to Name class and add @DBRef to the field in the UserInfo - Senior Pomidor
@SeniorPomidor, I had already tried that just in case. Just that it does not fit conceptually, also, it doesnot work. - Rajan Rawat
@dkb I dont get it. I have all the setters and getters, I checked the link and added a toString method and a constructor to the class Name. But still doesnot work. This is exactly what I want to know, what am I missing in the Class Name. it has getters and setter along with toString() which Iam afraid, is not what i think as I still get the json string without toString(), just that with NULL values. I thought it might be the constructor, but its not. - Rajan Rawat
okay, let me try, will update, if possible can you share your source code via github or bitbucket? - dkb

1 Answers

0
votes

In your document your attributes name are "first" and "last", so in your class Name you need to use the same names so that the object can be mapped by spring.

just try this:

public class Name {

private String first;
private String last;

}