【发布时间】:2019-12-23 22:58:53
【问题描述】:
Entity Parent 有多个一对多关联,如下所示。 子实体也有一对多的关联。
我成功编写了获取父实体和子实体的查询:
entityManager.createQuery("select p from Parent p " +
"left join fetch p.child1 " +
"left join fetch p.child2 " +
"where p.parentId = :parentId", Parent.class);
此查询执行后,将针对每个其他级别的子实体执行附加查询,因此针对子实体的每个子实体。
是否可以在一个查询中获取包含所有子实体和子实体的子实体的父实体?
对象看起来像:
public class Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long parentId;
\\other attributes
@OneToMany(
mappedBy = "parent",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Child1> child1= new HashSet<>();
@OneToMany(
mappedBy = "parent",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Child2> child2= new HashSet<>();
...
// other associations are removed because they are the same
//Constructors, getters and setters removed for brevity
}
public class Child1{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long child1Id;
\\other attributes
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
@OneToMany(
mappedBy = "child1",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<ChildOfChild1> childOfChild1= new HashSet<>();
//Constructors, getters and setters removed for brevity
}
public class Child2{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long child2Id;
\\other attributes
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
@OneToMany(
mappedBy = "child2",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<ChildOfChild2> childOfChild2= new HashSet<>();
//Constructors, getters and setters removed for brevity
}
【问题讨论】:
-
我已经尝试过了,但是父实体有 8 个一对多关联,所以当我实现 @EntityGraphs 服务时卡住并且无法完成获取..