Spring数据和mongoDB-继承和@DBRef [英] Spring data and mongoDB - inheritance and @DBRef
问题描述
我有这两个文档,用户:
I have this two documents, User:
@Document(collection = "User")
public class User {
// fields
}
和联系人:
@Document(collection = "Contact")
public class Contact extends User{
// fields
}
然后我有一个文档,它引用了用户oder联系人:
and then I have a document which referes either to User oder Contact:
@Document(collection = "DocumentFile")
public class DocumentFile {
@DBRef
private User user;
}
因此,我能够在DocumentFile#user中添加用户或联系人,但是如果我将Contact设置为DocumentFile#user,则会丢失引用,因为在MongoDB中,DocumentFile#user存储为"_class":"... Contact" . 有解决方案吗?
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?
推荐答案
这是您的类应如何使DBRef与继承一起工作的样子.
This is how your classes should look like to make the DBRef work with the inheritance.
用户
@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;
}
}
联系方式
请注意,您不需要在此类上的文档注释.
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(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;
}
}
CRUD操作只需要IDocumentFileRepository
和IUserRepository
.
You'll just need the IDocumentFileRepository
and IUserRepository
for CRUD operations.
其余的代码以及测试用例已上传到github.
Rest of the code along with the test cases have been uploaded to github.
https://github.com/saagar2000/Spring
这篇关于Spring数据和mongoDB-继承和@DBRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!