Multiple JOIN FETCH in one JPQL query

北城以北 提交于 2020-01-20 16:06:39

问题


I have below entities:

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 */
}

and I want fetch all categories with joined topics and joined posts using JPQL query. I was wrote query like below:

SELECT c FROM Category c JOIN FETCH c.topics t JOIN FETCH t.posts p WHERE ...

But I got the error

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

I found articles about this error, but these articles only describe situation where in one entity are two collections to join. My problem is a little different and I don't know How to solve it.

It is possible to do in one query?

Sorry for my bad english, but I usually speak in other language


回答1:


You can use a Child-Parent fetch strategy and recombine the entity tree from the result.

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



回答2:


Here is a working example of complex join and multiple 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);



回答3:


A workaround is to use @Query and @EntityGraph together, like it mentioned here use @Query and @EntityGraph together



来源:https://stackoverflow.com/questions/30088649/multiple-join-fetch-in-one-jpql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!