繁体   English   中英

如何使用join fetch通过一个查询获取父实体及其子实体及其子实体

[英]How to fetch Parent Entity with its Child Entities and their Child Entities with one query with join fetch

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);

执行此查询后,会为每个另一个级别的子实体执行附加查询,因此对于 child 的每个子实体。

是否可以在一个查询中获取具有所有子实体和子实体的子实体的父实体?

对象看起来像:

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

 }

你可以尝试使用这样的东西:

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);

看看这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM