我想从嵌入对象访问父对象,但找不到实现它的方法。我将在此处展示这意味着什么的示例:
我有 2 个这样的 Java 类:
@Document
public class Parent {
private String name;
private List<Child> children;
@PersistenceConstructor
public Parent (String name, List<Child> children) {
this.name = name;
this.children = children;
}
...
@Document
public class Child {
private String name;
private Parent parent;
@PersistenceConstructor
public Child(String name, Parent parent) {
this.name = name;
this.parent = parent;
}
...
我在MongoDB中的文档是这样的:
{
"name": "some name",
"children" : {
"name": "name1"
},
{
"name" : "name2"
}
}
是否有可能以某种方式获取对父类的引用,例如在 Child 类的构造函数中?似乎Child类中@PersistenceConstructor注解构造函数中的所有参数都必须来自children数组,这意味着名为parent的参数为null :(
我知道如果我创建自己的 Converter 实现,我可以反序列化 Parent 和 Child 并自己将父引用设置为 child,但我的实际文档非常大,必须自己编写反序列化代码是很多样板代码。
最佳答案
您可以做的是手动设置父引用:
在 child 中:
@Transient
private Parent parent;
public void setParent(Parent parent) {
this.parent = parent;
}
@Transient 注解告诉 spring data 在保存对象时忽略该字段。
然后在父级:
@PersistenceConstructor
public Parent (String name, List<Child> children) {
this.name = name;
this.children = children;
for (Child child : children) {
child.setParent(this);
}
}
并且通过一些巧妙的接口(interface)和辅助类或继承,重复代码的数量将最小化。
关于java - 从 Spring Data MongoDB 中的嵌入式文档获取对父文档的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21854907/