我有以下实体:
public class Category {
private Integer id;
@OneToMany(mappedBy = "parent")
private List<Topic> topics;
}
public class Topic {
private Integer id;
@OneToMany(mappedBy = "parent")
private List<Posts> posts;
@ManyToOne
@JoinColumn(name = "id")
private Category parent;
}
public class Post {
private Integer id;
@ManyToOne
@JoinColumn(name = "id")
private Topic parent;
/* Post fields */
}
我希望使用JPQL查询获取所有已加入主题的类别并加入帖子。我写了如下的查询:
SELECT c FROM Category c JOIN FETCH c.topics t JOIN FETCH t.posts p WHERE ...
但是我收到了错误
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
我发现了有关此错误的文章,但这些文章仅描述了在一个实体中要加入的两个集合的情况。我的问题有点不同,我不知道如何解决它。
可以在一个查询中执行吗?
抱歉我的英语不好,但我通常会说其他语言
答案 0 :(得分:32)
您可以使用Child-Parent fetch strategy并从结果中重新组合实体树。
SELECT p
FROM Post p
JOIN FETCH p.topic t
JOIN FETCH t.category c
WHERE ...
答案 1 :(得分:4)
这是一个复杂连接和多个consition的工作示例:
String query_findByProductDepartmentHospital = "select location from ProductInstallLocation location "
+ " join location.product prod " + " join location.department dep "
+ " join location.department.hospital hos " + " where prod.name = :product "
+ " and dep.name.name = :department " + " and hos.name = :hospital ";
@Query(query_findByProductDepartmentHospital)
ProductInstallLocation findByProductDepartmentHospital(@Param("product") String productName,@Param("department") String departName, @Param("hospital") String hospitalName);
答案 2 :(得分:0)
解决方法是一起使用@Query和@EntityGraph,就像这里提到的那样use @Query and @EntityGraph together