【发布时间】:2021-05-30 11:30:52
【问题描述】:
目前我有三个实体Country、Office 和用户,其中Country.gov 的类型为Office,而Office.holder 的类型为User。 Country 是Country.gov 的拥有方,Office 是Office.holder 的拥有方。
现在我想使用 Country 属性在 Office.holder 上获得带有 LEFT JOIN 的 Country.gov,例如
SELECT c.gov o FROM Country c LEFT JOIN FETCH c.gov LEFT JOIN FETCH c.gov.holder WHERE c.countryKey = :countryKey,但是这样不行,会抛出异常:
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
[FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=dev.teamnight.game.entities.Country.gov,tableName=office,tableAlias=office1_,origin=country country0_,columns={country0_.gov_id,className=dev.teamnight.game.entities.Office}}]
[SELECT c.gov FROM dev.teamnight.game.entities.Country c LEFT JOIN FETCH c.gov LEFT JOIN FETCH c.gov.holder WHERE c.countryKey = :countryKey]
【问题讨论】:
-
我找到了使用
SELECT o FROM Office o LEFT JOIN FETCH o.holder LEFT JOIN FETCH Country c ON c.gov = o WHERE c.countryKey = :countryKey的解决方案。也许有人可以解释为什么会这样,如果我能做得更好