如何使用连接获取一个查询来获取具有其子实体及其子实体的父实体

时间:2019-12-23 22:58:53

标签: java hibernate jpa

实体父级具有多个一对多关联,如下所示。 子实体也有一对多的关联。

我成功编写了一个查询,该查询可通过子实体获取父实体:

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

 }

1 个答案:

答案 0 :(得分:0)

您可以尝试使用类似这样的内容:

entityManager.createQuery("select p from Parent p " +
   "left join fetch p.child1 child1_ " +
   "left join fetch child1_.childOfChild1 " +
   "left join fetch p.child2 child2_ " +
   "left join fetch child2_.childOfChild2 " +
   "where p.parentId = :parentId", Parent.class);

看看this