2015-05-06 53 views
11

取我有以下實體:多加入一個JPQL查詢

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 

我發現這個錯誤的文章,但這些文章只是介紹情況下在一個實體的兩個集合加入。我的問題有點不同,我不知道如何解決它。

可以在一個查詢中做?

對不起我的英語不好,但我通常在其他語言說話

回答

22

您可以使用Child-Parent fetch strategy,並從結果重組是實體樹。

SELECT p 
FROM Post p 
JOIN FETCH p.topic t 
JOIN FETCH t.category c 
WHERE ... 
+1

在爲此文章中說過:「儘管簡單地使用索引列表或集合總是更好的」。如何創建索引列表? – Zaprogramowany

+0

這是另一個問題的主題,我相信它已經在SO上得到解答。 –

1

這裏是複雜的工作示例加入和多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);