Join fetch 在获取第三级关系时失败

Join fetch fails on fetching 3rd level relationship

我有三个实体:PersonCountryCountryTranslationPerson 与一个 Country 相关,而 Country 有多个 CountryTranslations

我希望我的查询在获取 Person 时同时获取 CountryCountryTranslations,以避免多次查询。

要将 CountryPerson 一起使用,我这样做:

List<Person> persons = (List<Person>) entityManager
                .createQuery("SELECT person from Person person " +
                             "left join fetch person.country")
                .getResultList()

这很好用,我在休眠中看到它很好地获取并且没有执行额外的查询来带来 Country,但是为了带来 CountryTranslations 它仍然执行额外的查询。然后我试了:

List<Person> persons = (List<Person>) entityManager
                .createQuery("SELECT person from Person person " +
                             "left join fetch person.country " +
                             "left join fetch person.country.translations")
                .getResultList()

我收到错误:

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list 

执行此抓取的正确方法是什么?

提前致谢

您更正此问题,为每个关系指定一个别名。

SELECT person 
FROM  person person 
LEFT JOIN FETCH person.country country 
LEFT JOIN FETCH country.translations

这是框架的"limitation":当您使用链接获取时,您应该为每个关系指定一个别名!

这种行为也可以解释,因为很难理解这些链接提取的真正含义:框架会提取每个关系还是只提取最后一个?直接告诉框架你想要什么样的 fetch 关系就更简单了。