加载 child 未加载 parent
Loading child doesn't load parent
我有以下实体
Parent(
id PK,
name VARCHAR
//more fields
);
而我的childtable是
Child(
id PK,
parentId FK,
name VARCHAR
);
在我的 java 实体中,我的 parent 定义为
@Entity
class Parent{
@Id
private int id;
@OneToMany(mappedBy = "parents")
@JsonManagedReference
private Set<Child> children;
}
我的Childclass是
@Entity
class Child{
@Id
private int id;
@ManyToOne
@JoinColumn(name = "parendId")
@JsonManagedReference
private Parent parent;
}
然后我有 ChildRepo
用下面的方法。该方法执行正常,但我变空了 parent。
这里是查询
@Query("select c from Child c where c.name is not null")
List<Child> getAllChildrenWithName();
P.S:我使用 JsonManagedReference
和 JsonBackReference
来避免递归,同时通过 Json 发送回实体。
将您的查询更改为以下内容:
@Query("select c from Child c LEFT JOIN c.parent p where c.name is not null")
如果您使用内部联接,并且子项未关联到父项,则查询结果可能为空。
我有以下实体
Parent(
id PK,
name VARCHAR
//more fields
);
而我的childtable是
Child(
id PK,
parentId FK,
name VARCHAR
);
在我的 java 实体中,我的 parent 定义为
@Entity
class Parent{
@Id
private int id;
@OneToMany(mappedBy = "parents")
@JsonManagedReference
private Set<Child> children;
}
我的Childclass是
@Entity
class Child{
@Id
private int id;
@ManyToOne
@JoinColumn(name = "parendId")
@JsonManagedReference
private Parent parent;
}
然后我有 ChildRepo
用下面的方法。该方法执行正常,但我变空了 parent。
这里是查询
@Query("select c from Child c where c.name is not null")
List<Child> getAllChildrenWithName();
P.S:我使用 JsonManagedReference
和 JsonBackReference
来避免递归,同时通过 Json 发送回实体。
将您的查询更改为以下内容:
@Query("select c from Child c LEFT JOIN c.parent p where c.name is not null")
如果您使用内部联接,并且子项未关联到父项,则查询结果可能为空。