2009-09-15 78 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) 
    } 
}