2015-02-24 60 views
0

我有很多一對多的關係:的Grails查詢:獲取關聯對象的名單

class Project { 
    Set<PrincipalInvestigator> pis 
    : 

    static hasMany = [ pis:PrincipalInvestigator ] 
} 

class PrincipalInvestigator { 
    String name 
    : 
} 

我想返回屬於一個預先定義的列表督察的獨特和排序列表查詢的項目。

一個天真的方法是迭代通過項目,並迭代通過他們的PI列表,同時刪除欺騙。這樣做的代碼很簡單,但速度很慢。

到目前爲止,最好的有效的解決方案我能想出是:

def pi_ids = Project.createCriteria().list{ // find unique list of PI IDs 
    // project filters here, not relevant to the question 
    createAlias('pis', 'aka_pis', JoinType.LEFT_OUTER_JOIN) 
    isNotNull('aka_pis.id') 
    projections { 
     distinct('aka_pis.id') 
    } 
} 
def pi_list = PrincipalInvestigator.createCriteria().list{ // get PIs from list of IDs 
    inList('id', pi_ids) 
    order('name', 'asc') 
} 

我的解決辦法是幅度快一個數量級,但它仍然是2個不同的查詢。有沒有辦法在單個查詢中獲得相同的結果?

回答

0

解決我的問題是這樣的HQL:

PrincipalInvestigator.executeQuery(
    "select distinct pi from Project p inner join p.pis as pi where p.id in :projectIds order by pi.name", 
    [projectIds:[1,2,3]]) 

該解決方案允許對不同的結果進行排序和內加入微調的所有空實例。感謝cfrick讓我走上正軌。

0

使用executeQuery使查詢變得更容易。沿着下面的東西應該工作:

PrincipalInvestigator.executeQuery("select distinct p.pis from Project p where p.id in :projectIds", 
    [projectIds: [1,2,3]]) 
+0

謝謝。你如何使PI列表唯一(編輯「選擇不同」)並妥善排序? – sebnukem 2015-02-24 18:21:58

+0

@sebnukem編輯,只需添加'distinct' – cfrick 2015-02-24 18:29:30