2012-05-04 43 views
3

我需要一種方法在Grails/Hibernate中執行「所有」條件查詢。標準的「進入」限制是我所稱的「任何」限制。「全部」限制Grails/Hibernate標準查詢

舉例來說...

序言

拿域類「騎士」具有與其他領域類的「風險」一多對一對多的關聯。這些類簡單...

class Knight { 
    String name 
    static hasMany = [perils:Peril] 
} 

class Peril { 
    String name 
    static hasMany = [knights:Knight] 
    static belongsTo = Knight 
} 

表的內容是這樣的...

 
    Knights 
    1 Arthur, King of the Britains (Not technically a knight. I know, I know.) 
    2 Sir Bedevere the Wise 
    3 Sir Lancelot the Brave 
    4 Sir Robin the Not-Quite-So-Brave-As-Sir-Lancelot 
    5 Sir Galahad the Pure 

    Perils 
    1 Black Knight 
    2 Knights who say Ni 
    3 Three-Headed Giant 
    4 Swamp Castle 
    5 Castle Anthrax 
    6 Rabbit of Caerbannog 

    Knights_Perils 
    1, 1  // arthur fights the black knight 
    1, 2  // arthur fights the knights who say ni 
    2, 2  // bedevere fights the knights who say ni 
    4, 3  // Robin runs-away from Three-Headed Giant 
    3, 4  // Lancelot Assaults Swamp Castle 
    5, 5  // Galahad visits Castle Anthrax 
    3, 5  // Lancelot "rescues" Galahad from Castle Anthrax 
    1, 6  // All Knights fight the Killer Bunny 
    2, 6  // ... 
    3, 6  // ... 
    4, 6  // ... 
    5, 6  // ... 

我提出一個形式,提供複選框在關聯搜索...

 
    Choose Perils and Search for Knights... 
    [ ] Black Knight (id 1) 
    [ ] Knights who say Ni (id 2) 
    [ ] Three-Headed Giant (id 3) 
    [x] Swamp Castle (id 4) 
    [x] Castle Anthrax (id 5) 
    [x] Killer Bunny (id 6) 

    [search] 

而我這樣查詢:

def query = Knights.createQuery() 
query.list(max: params.max, offset: params.offset) { 
    if(params.perils) perils { 'in' ('id', params.list('perils')*.toLong()) } 
} 

這產生了我所說的「任何」結果。騎士與一個協會「在任何」的檢查風險清單。在3的情況下,簽在上面的表格危險,所有的騎士......

 
    Arthur - fights bunny 
    Bedevere - fights bunny 
    Lancelot - swamp castle, castle anthrax, fights bunny 
    Robin - fights bunny 
    Galahad - castle anthrax, fights bunny 

問題

我正在尋找一個Hibernate/Grails的標準限制類似「中」但那會查詢「全部」。換句話說,奈特與列表中的所有檢查風險有關聯。有了這個限制,並且上述相同的形式輸入,我希望的結果是隻有

 
    Lancelot - swamp castle, castle anthrax, fights bunny 

是否有一個「所有」的「中」限制Hibernate的標準版本?記住,我想用CriteriaQuery(無論是Hibernate還是Grails方言),而不是直接的SQL或HQL做到這一點。

任何關於如何解決這個問題的指針?

謝謝!

  • 加里

回答

1

好問題。也許有一個更好的選擇,因爲我不知道SQL/HQL的每一個方面,但以下條款:

all the selected perils are in the knight's perils 

也可以這樣表示

there is no peril in the selected perils that is not in the knight's perils 

所以,HQL,你可以這樣表達:

select knight from Knight knight 
where not exists (select peril.id from Peril peril 
        where peril.id in :selectedPerilIds 
        and peril.id not in (select peril2.id from Peril peril2 
             where peril2.knight.id = knight.id))