【问题标题】:Hibernate HQL "Path expected for join!" @ManyToOne relationshipHibernate HQL“预期加入的路径!” @ManyToOne 关系
【发布时间】:2017-07-22 02:54:12
【问题描述】:

假设有两个实体——所有者

@Entity
@NamedQueries({
   @NamedQuery(name = "Owner.findOwnerForPetId", query = "select o from Owner o inner join Pet p on o.ownerId=p.owner.ownerId where p.petId= :petId")
})
public class Owner {

  @Id
  @Column(name = "ownerId")
  private Long ownerId;

  @Column
  private String name;

  // scaffolding code...
}

和宠物

@Entity
public class Pet {

  @Id
  @Column(name = "petId")
  private Long petId;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "ownerId")
  private Owner owner;

  @Column
  private String name;

  // scaffolding code...
}

其中一个所有者可以拥有多个宠物(原类已重命名),但一个宠物只能属于一个所有者。我想做的是找到拥有具有某些 id 的宠物的所有者,例如:

select Owner.ownerId, Owner.name from Owner inner join Pet on Owner.ownerId=Pet.ownerId where Pet.petId=3;

当在纯 SQL 中执行时,这可以正常工作。但是,我在 HQL 中尝试了这两个查询,它们都给出了错误Path expected for join!

select o from Owner o inner join Pet p on o.ownerId=p.owner.ownerId where p.petId= :petId

from Owner o join Pet p where p.petId= :petId

请注意,所有者中没有 @OneToManyCollection<Pet> pets。我想在 Pet 端只使用 @ManyToOne

关于我错过了什么的任何提示?

【问题讨论】:

  • "Path expected" 意味着Owner 没有办法访问这些宠物,除非它把它们存储在一个集合中。我相信你必须让Owner保留宠物的收藏。

标签: java sql hibernate jpa hql


【解决方案1】:

试试这个

  select o from Pet p inner join p.owner o where p.petId= :petId

【讨论】:

    【解决方案2】:

    使用 HQL 时,您必须使用实体之间的关系而不仅仅是实体

    所以对于 INNER JOINLEFT JOIN,例如您应该使用直接关系

    例如接下来是有效的查询

    SELECT o FROM Pet p inner join p.owner o WHERE p.petId= :petId (与@rathna 接受的答案相同)

    从宠物中选择 p p WHERE p.owner.ownerId = :ownerId

    【讨论】:

      【解决方案3】:

      为了完整起见,如果您需要LEFT JOIN,但右侧有@ManyToOne属性,因此无法指定路径,您可以将查询转换RIGHT JOIN,效果相同(即不丢失其他表没有匹配行的行,过滤其他表而不丢失空行) .

      假设您想让所有没有宠物的主人忽略名为 Charly 的宠物:

      你不能指定

      SELECT o
      FROM Owner o
      LEFT JOIN o.pet p (<-------- ERROR) WITH p.name != 'Charly'
      GROUP BY o.ownerId
      HAVING count(p.petId) = 0
      

      但您可以将其转换为:

      SELECT o
      FROM Pet p
      RIGHT JOIN p.owner o WITH p.name != 'Charly'
      GROUP BY o.ownerId
      HAVING count(p.petId) = 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多