2012-10-02 31 views
0

我有以下域類HQL爲了通過最大項子列表

class Child{ 
    def age 
} 

class Parent{ 
    static hasMany = [children:Child] 
} 

,我想執行的HQL以下

Parent.list() 
    .sort{ parent -> parent.children.sort{ child -> child.age}[0]}[0..10] 

基本上我想檢索列表父母按照其最大孩子的年齡排序。並限制爲只有10條記錄。我不想從數據庫中提取所有父和子記錄,然後進行必要的排序。我希望HQL可以在'數據庫層'上做到這一點,並只返回我需要的結果。謝謝:)

回答

1
Parent.withCriteria { 
     createAlias('children', 'ch', org.hibernate.criterion.CriteriaSpecification.LEFT_JOIN) 
     order("ch.age", "desc") 
     maxResults(10) 

     setResultTransformer(org.hibernate.criterion.CriteriaSpecification.DISTINCT_ROOT_ENTITY) 
    }