Search code examples
javamongodbdbref

get dbref from document in Mongo using Java


I cannot get dbRef object from Mongo. In my entity package I have a User class with a Parent class inheriting. Here is the User class:

public class User {

@Id
private ObjectId id;

@DBRef
private Account account;

private String name;

public String getId() {
    if (id != null) {
        return id.toStringMongod();
    }           

    return null;//no id
}

public void setId(ObjectId objectId) {
    this.id = objectId;
}

public Account getAccount() {
    return account;
}

public void setAccount(Account account) {
    this.account = account;
}
public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}
}

As you can see above, I am putting an object of Account here. My Parent class simply extends User:

@Document
public class Parent extends User {

@JsonProperty("is_activated")
private boolean isActivated;

public boolean isActivated() {
    return isActivated;
}

public void setActivated(boolean isActivated) {
    this.isActivated = isActivated;
}
}

Note: nothing magic with isActivated.

In my ParentDaoImpl class:

@Service
public class ParentDaoImpl extends AbstractDaoImpl implements ParentDao {

@Override
public Parent getParentByLogin(String login) {
    Query query = new Query(Criteria.where("login").is(login));
    return mongoOperations.findOne(query, Parent.class, "parents");
}
}

The problem is that if I call getParentByLogin method, it returns evertyning but Account field is null. Maybe findOne doesn't give dbRef inside. I think in relational Databases, there would be something like join. I want my method to give me account field as well.

Thanks for your help!


Solution

  • Can you try something like this.

    ....
    @Field("fieldName")
    @DBRef(collection = "mongoCollectionName")
    private Account account;
    ....