2012-03-15 62 views
1

我正在使用Hibernate映射到我無法更改的遺留數據模型。對於特定的查詢,我試圖構建一些使用包含多個屬性的連接條件的HQL。我有一個可怕的人爲的例子,說明什麼,我想實現:Hibernate條件HQL加入

考慮類Consumer和它的兩個特性 - 無論Gadget類型:

@Table(name = "consumer") 
class Consumer { 
    @Column(name = "mp3_player") 
    Gadget mp3Player; 
    @Column(name = "mobile_phone") 
    Gadget mobilePhone; 
    ... 

注意,consumer表有兩個外鍵gadget表 - 不理想 - 但這是我必須與之合作。我想獲得名爲'iphone'的Gadgets列表,Consumer'bob'用作MP3播放器或電話。用postgres我可以寫:

select gadget.* 
from consumer join gadget on (
    consumer.mp3_player = gadget.id or consumer.mobile_phone = gadget.id 
) 
where consumer.name = 'bob' and gadget.name = 'iphone'; 

我試圖用HQL來表達這個查詢,但它似乎要求連接子句只包含一個條件。那麼如何在HQL中表達類似的查詢呢?

回答

1
select consumer from Consumer consumer 
left join consumer.mp3Player mp3Player 
left join consumer.mobilePhone mobilePhone 
where consumer.name = 'Bob' 
and (mp3Player.name = 'iphone' or mobilePhone.name = 'iphone') 
+0

感謝您的回覆 - 我意識到我錯過了一些細節問題,所以現在就更新。 – teabot 2012-03-16 11:55:34

+0

好的,事實證明我問的是錯誤的問題 - 我的歉意。這個問題現在已經更新。 – teabot 2012-03-16 11:59:19