【问题标题】:Select attribute of another attribute of entity选择实体的另一个属性的属性
【发布时间】:2021-05-30 11:30:52
【问题描述】:

目前我有三个实体CountryOffice 和用户,其中Country.gov 的类型为Office,而Office.holder 的类型为User。 Country 是Country.gov 的拥有方,Office 是Office.holder 的拥有方。

现在我想使用 Country 属性在 Office.holder 上获得带有 LEFT JOINCountry.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 的解决方案。也许有人可以解释为什么会这样,如果我能做得更好

标签: spring hibernate jpa jpql


【解决方案1】:

您可以稍微简化一下您的查询:

List<Office> calls = entityManager.createQuery(
    "select o " +
    "from Country c " +
    "join c.gov o " +
    "left join fetch o.holder " +
    "where c.countryKey = :countryKey ", Office.class )
.setParameter( "countryKey", countryKey )
.getResultList();

如需更多解释,请参阅 hibernate 文档的 this section

【讨论】:

    猜你喜欢
    • 2017-01-29
    • 2014-12-03
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2016-06-15
    相关资源
    最近更新 更多