【发布时间】:2019-06-17 02:23:48
【问题描述】:
我有三个实体:Person、Country 和 CountryTranslation。
Person 与一个Country 相关,而Country 有多个CountryTranslations。
我希望我的查询在获取Person 时同时获取Country 和CountryTranslations,以避免多次查询。
要带上Country 和Person 我愿意:
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