【问题标题】:Join fetch fails on fetching 3rd level relationship获取第三级关系时加入获取失败
【发布时间】:2019-06-17 02:23:48
【问题描述】:

我有三个实体: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 

进行此获取的正确方法是什么?

提前致谢

【问题讨论】:

  • 你可以尝试删除“fetch”关键字吗?这样 Hibernate 不会在 Select 子句中包含关联;详情可到discourse.hibernate.org/t/…
  • 尝试改成SELECT person from Person person left join fetch person.country country left join fetch country.translations"
  • @HenriqueMentz 这成功了。给它一个别名。不知道有没有原因?

标签: java hibernate jpa hql jpql


【解决方案1】:

您更正此问题,为每个关系提供别名。

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

这是一个框架的“限制”:当您使用链接提取时,您应该为每个关系指定一个别名!

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

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2019-07-23
    相关资源
    最近更新 更多