Grails查询:获取关联对象的列表

时间:2015-02-24 17:50:43

标签: grails gorm hibernate-criteria

我有多对多的关系:

class Project {
    Set<PrincipalInvestigator> pis
     :

    static hasMany = [ pis:PrincipalInvestigator ]
}

class PrincipalInvestigator {
    String name
     :
}

我想要一个查询,该查询返回属于预定义项目列表的唯一且已排序的PI列表。

一种天真的方法是通过项目进行迭代,并通过他们的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个不同的查询。有没有办法在单个查询中获得相同的结果?

2 个答案:

答案 0 :(得分:0)

使用executeQuery可以更轻松地进行查询。以下内容应该有效:

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

答案 1 :(得分: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让我走上正轨。