我有三個實體Person:Country和CountryTranslation。 Person與一個有關,Country并Country有許多CountryTranslations。我希望我的查詢同時獲取Country以及CountryTranslations何時獲取 aPerson以避免多個查詢。帶著我Country一起Person做:List<Person> persons = (List<Person>) entityManager .createQuery("SELECT person from Person person " + "left join fetch person.country") .getResultList()這工作正常,我在休眠時看到它很好地獲取并且沒有執(zhí)行額外的查詢來帶來Country,但帶來CountryTranslations它仍然執(zhí)行額外的查詢。然后我嘗試了: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 進行此獲取的正確方法是什么?
1 回答

滄海一幻覺
TA貢獻1824條經(jīng)驗 獲得超5個贊
您更正此問題,為每個關系提供別名。
SELECT person
FROM person person
LEFT JOIN FETCH person.country country
LEFT JOIN FETCH country.translations
這是一個框架的“限制”:當您使用鏈接獲取時,您應該為每個關系指定一個別名!
這種行為也可以解釋,因為很難理解這些鏈接獲取的真正含義:框架將獲取每個關系還是只獲取最后一個關系?告訴框架你想要什么獲取關系更簡單。
添加回答
舉報
0/150
提交
取消