2010-04-20 70 views
0

我很熟悉SQL/HQL,和我目前仍堅持這一「也許」簡單的問題:Hibernate的HQL M:N加盟問題

我有兩個多到許多實體,有關係表:

Car,CarProblem,and Problem。

一輛汽車可能有很多問題,

一個問題可能出現在很多汽車,

CarProblem是與其他屬性的關聯表。

現在,我想找到具有指定問題的Car(s),我該如何編寫這樣的HQL? 所有ID都是長型。

我已經嘗試了很多加盟/內加入組合,但一切都是徒勞..

- 更新:

對不起,忘了提:

汽車有許多CarProblem

問題有許多CarProblem

汽車和問題不直接相連的Java對象。

- 更新,下面的Java代碼 -

@Entity 
public class Car extends Model{ 
    @OneToMany(mappedBy="car" , cascade=CascadeType.ALL) 
    public Set<CarProblem> carProblems; 
} 

@Entity 
public class CarProblem extends Model{ 
    @ManyToOne 
    public Car car;  
    @ManyToOne 
    public Problem problem;  
    ... other properties 
} 


@Entity 
public class Problem extends Model { 
    other properties ... 
    // not link to CarProblem , It seems not related to this problem 

    // **This is a very stupid query , I want to get rid of it ...** 
    public List<Car> findCars() 
    { 
    List<CarProblem> list = CarProblem.find("from CarProblem as cp where cp.problem.id = ? ", id).fetch(); 
    Set<Car> result = new HashSet<Car>(); 
    for(CarProblem cp : list) 
     result.add(cp.car); 

    return new ArrayList<Car>(result); 
    } 
} 

該模型是從玩遊戲!框架,所以這些屬性都是公開的。

+1

顯示您的代碼/映射 – 2010-04-20 20:42:41

回答

2

我就乾脆質疑的CarProblem的需要,但如果你要保持這種映射,我相信你可以做這樣的事情:

select c from CarProblem as cp join cp.car as c join cp.problem as p where p.id = :id 
+0

謝謝,它工作! 順便說一句,我保持CarProblem實體的原因是這裏還有其他屬性。 – smallufo 2010-04-20 21:16:52

+0

是的,我看到「...其他屬性」,我認爲你的映射是你的業務,所以我只剩下那個......大多數:) – digitaljoel 2010-04-20 21:21:42

0

假設一切都已經正確映射:

from Car c join c.problems p where p.id = :id

+0

對不起,我忘記提及車不直接鏈接到問題。 汽車有很多CarProblems。 問題有很多CarProblems。 – smallufo 2010-04-20 20:32:22

+1

你能否提供你的映射?你有兩個一對多的關係? – serg 2010-04-20 20:40:46

+0

謝謝,我在我的問題中追加了我的代碼。它用於Play!框架。我想在Problem.findCars()中使用一行HQL ... – smallufo 2010-04-20 20:59:06