【问题标题】:How to fetch Parent Entity with its Child Entities and their Child Entities with one query with join fetch如何通过一个带有连接提取的查询来获取父实体及其子实体及其子实体
【发布时间】: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 服务时卡住并且无法完成获取..

标签: java hibernate jpa


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2020-01-04
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多