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?
When the relationship between the entities is already defined, you can use the join fetch
syntax:
select mo from Person mo join fetch mo.cars c where c.model = ?
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:
select p from Person p
inner join p.cars car
where car.model = :model
As always, the relevant documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With