Illegal attempt to dereference a collection when querying using JPA relationships

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 am trying to query people by model. The following code fails , although the connections between the tables are clear:

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

Mistake:

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 solve the problem?

+4
source share
2 answers

When the relationship between the entities is already defined, you can use the syntax join fetch:

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

mo.carsis a set. You cannot access the property of the Set model because it does not have it. You need to join:

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

As always, relevant documentation .

+4

Source: https://habr.com/ru/post/1625706/


All Articles