2

I have this two documents, User:

@Document(collection = "User")
public class User {
    // fields
}

and Contact:

@Document(collection = "Contact")
public class Contact extends User{
    // fields
}

and then I have a document which referes either to User oder Contact:

@Document(collection = "DocumentFile")
public class DocumentFile {

    @DBRef
    private User user;
}

So I am able to add User oder Contact in DocumentFile#user but if I set a Contact to DocumentFile#user than I lost the reference because in MongoDB DocumentFile#user is stored as "_class" : "...Contact". Is there a solution for that?

3
  • I solved it with two different fields in DocumentFile but I would still be interested in how to do it in the way of inheritance with basic type User Commented Dec 15, 2016 at 6:54
  • What do you mean by losing the reference ? Do you problem getting data back ? Commented Dec 17, 2016 at 8:41
  • Yes, because the _class type in DocumentFile document is ...User (also if it is a Contact- reference) but it should be ...Contact and therefore when I retrieve a documentFile than user field is null. Commented Dec 17, 2016 at 18:42

1 Answer 1

6
+50

This is how your classes should look like to make the DBRef work with the inheritance.

User

@Document(collection = "User")
public class User {

    @Id
    private String id;
    public String getId() {
        return id;
    }

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

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Contact

Please note you don't need Document annotation on this class.

public class Contact extends User {

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Document File

@Document(collection = "DocumentFile")
public class DocumentFile {

    @Id
    private String id;

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

    @DBRef
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

You'll just need the IDocumentFileRepository and IUserRepository for CRUD operations.

Rest of the code along with the test cases have been uploaded to github.

https://github.com/saagar2000/Spring

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.