一尘不染

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

hibernate

我有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 = ?]

任何想法如何解决该问题?


阅读 266

收藏
2020-06-20

共1个答案

一尘不染

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

select mo from Person mo join fetch mo.cars c where c.model = ?
2020-06-20