在使用JPA关系查询时非法尝试取消引用集合

时间:2016-01-24 11:57:46

标签: java hibernate jpa

我有2个班级:

@Table(name = "PEOPLE")
@Entity
class Person {
  @OneToMany(mappedBy = "owner")
  Set<Car> cars;
}
@Table(name = "CARS")
@Entity
class Car {
  @ManyToOne
  @JoinColumn(name = "OWNER_ID", referencedColumnName = "ID")
  Person owner;
  @Column(name = "MODEL")
  String model;
}

我试图按模型查询人物。运行以下代码失败,即使表之间的连接是明确的:

select mo from Person mo where mo.cars.model = ?

错误是:

org.hibernate.QueryException: illegal attempt to dereference collection [...] with element property reference [model] [select mo from Person mo where mo.cars.model = ?]

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:10)

当已定义实体之间的关系时,您可以使用join fetch语法:

select mo from Person mo join fetch mo.cars c where c.model = ?

答案 1 :(得分:6)

mo.cars是一个集合。您无法访问Set的model属性,因为它没有。您需要加入:

 select p from Person p 
 inner join p.cars car
 where car.model = :model

与往常一样,the relevant documentation