2010-06-29 66 views
0

我有一個連接表的兩個對象之間的多對多關係。我需要能夠根據父母和日期選擇5個隨機孩子,排除一些兒童記錄。我被卡住了。有任何想法嗎?獲取與namedQuery的多對多關係的隨機記錄

Parent { 
     static hasMany = [children: Child] 
    } 

    Child { 
     Date dob 
     static belongsTo = [Parent] 
     static hasMany = [parents: Parent] 

     static namedQueries { 

     randomFiveChildrenBornAfter { parentid, dob, excludeChildren-> 

      qt 'dob', dob    
      parents { 
      eq 'id',parentid 
      } 
      // not in(excludeChildren) ?? order by rand() ?? 
     } 
     } 
    } 

回答

2

這些字面上的父/子關係(如人類)?如果是這樣,那麼這組子代可能非常小,我可能只是在內存中執行它,而不是通過sql查詢。

parent.children 
    .findAll { dob >= fiveYearsAgo } 
    .sort { Math.random() } 
    .with { it.size() >= 5 ? it.subList(0,5) : it } 
+0

感謝特德爲您的答覆。不幸的是,它不是文字和父對象可以有成千上萬的孩子,所以它會花費相當昂貴的做它在內存中...任何方式來使用標準查詢做到這一點? – Micor 2010-06-30 04:58:34

+0

在這種情況下,您必須在數據庫中執行此操作。不幸的是,沒有一個數據庫不可知的獲取隨機行的方式。有關如何編寫HQL條件以獲取具有限制的隨機行的詳細信息,請參閱此stackoverflow後期:http://stackoverflow.com/questions/2810693/hibernate-criteria-api-get-n-random-rows – 2010-07-01 00:35:52

+0

巧妙的技巧sqlRestriction。它必須這樣做。謝謝。 – Micor 2010-07-02 01:07:05

0

,如果你想使用withCriteria方法最好的解決方法是這樣的:

User.withCriteria{ 
eq 'name', 'joseph' 
sqlRestriction " order by rand()" 
} 

說,有時(取決於創造條件查詢)有必要增加一個「1這一點很重要= 1「在sqlRestriction中導致它在生成的查詢中添加」和「條件。 所以,如果你有一個方形例外使用:

sqlRestriction " 1=1 order by rand()"