Java 一个 JPQL 查询中的多个 JOIN FETCH

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30088649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:06:41  来源:igfitidea点击:

Multiple JOIN FETCH in one JPQL query

javahibernatejpajoinjpql

提问by Zaprogramowany

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:

并且我想使用 JPQL 查询获取所有带有连接主题和连接帖子的类别。我写了如下查询:

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

抱歉我的英语不好,但我通常会说其他语言

采纳答案by Vlad Mihalcea

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

您可以使用Child-Parent fetch 策略并从结果中重新组合实体树。

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

回答by wangf

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

回答by koly

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

一种解决方法是将@Query 和@EntityGraph 一起使用,就像这里提到的那样将@Query 和@EntityGraph 一起使用