Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal attempt to dereference collection when querying using JPA relations

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?

like image 622
AlikElzin-kilaka Avatar asked Jan 24 '16 11:01

AlikElzin-kilaka


2 Answers

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 = ?
like image 64
planben Avatar answered Oct 21 '22 21:10

planben


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.

like image 7
JB Nizet Avatar answered Oct 21 '22 19:10

JB Nizet