java 使用 JPA 关系查询时非法尝试取消引用集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34975468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Illegal attempt to dereference collection when querying using JPA relations
提问by AlikElzin-kilaka
I have 2 classes:
我有两个班级:
@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;
}
I'm trying to query people by model. Running the following code fails, even though the connections between the tables are clear:
我正在尝试按模型查询人员。运行以下代码失败,即使表之间的连接是明确的:
select mo from Person mo where mo.cars.model = ?
The error is:
错误是:
org.hibernate.QueryException: illegal attempt to dereference collection [...] with element property reference [model] [select mo from Person mo where mo.cars.model = ?]
Any idea how to resolve the issue?
知道如何解决这个问题吗?
回答by planben
When the relationship between the entities is already defined, you can use the join fetch
syntax:
当实体之间的关系已经定义时,您可以使用以下join fetch
语法:
select mo from Person mo join fetch mo.cars c where c.model = ?
回答by JB Nizet
mo.cars
is a Set. You can't access the model property of a Set, because it doesn't have one. You need a join:
mo.cars
是一个集合。您无法访问 Set 的模型属性,因为它没有。您需要加入:
select p from Person p
inner join p.cars car
where car.model = :model
As always, the relevant documentation.
与往常一样,相关文档。