2016-01-24 57 views
4

查詢時非法嘗試取消引用集合我有2類:使用JPA關係

@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 = ?] 

不知道如何解決這個問題?

+0

*順便說一句,這是一個簡單的例子。失敗的代碼有幾個'OneToMany'連接。它更像是一棵樹,條件是在一片樹葉上。 –

+0

所以請閱讀JPA規範或任何JPQL文檔,並看到您不能取消引用這樣的集合 –

回答

5

當已經定義的實體之間的關係,你可以使用join fetch語法:

select mo from Person mo join fetch mo.cars c where c.model = ? 
4

mo.cars是一組。您無法訪問Set的模型屬性,因爲它沒有。您需要加入:

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

一如既往,the relevant documentation