2009-09-15 76 views
1

我有以下的Grails域對象GORM的Hibernate查詢

class ProductType { 
    String name 
    static hasMany = [attributes: Attribute] 
} 

class Attribute { 

    Boolean mandatory = false 
    Integer seq 

    static belongsTo = [productType: ProductType] 
} 

我想獲得的所有ProductType S和他們的強制性Attribute秒。此外,我希望所選的Attribute s被熱切加載並按seq屬性排序。我試過各種HQL和Criteria查詢,但似乎無法弄清楚。

回答

1

這個查詢將返回具有強制性屬性的所有ProductTypes,與即時加載這些屬性:

def types = ProductType.executeQuery(""" 
    select distinct type from ProductType type 
    left join fetch type.attributes attribute 
    where attribute.mandatory=true""") 

的屬性在映射的設置,所以沒有訂貨,但是它很容易收集,整理它們:

def sortedAttributes = types.collect { it.attributes }.flatten().sort { it.seq } 
1

或者,您也可以通過實現在許多邊域進行比較的接口,並在一側(而不是默認設置)注入的SortedSet得到很多方面的排序列表。

class ProductType { 
    String name 
    SortedSet attributes 
    static hasMany = [attributes: Attribute] 
} 

class Attribute implements Comparable { 

    Boolean mandatory = false 
    Integer seq 

    static belongsTo = [productType: ProductType] 

    int compareTo(obj) { 
     seq.compareTo(obj.seq) 
    } 
}