我有以下Grails域对象

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

class Attribute {

    Boolean mandatory = false
    Integer seq

    static belongsTo = [productType: ProductType]
}

我想获取所有 ProductType 及其必需的 Attribute 。此外,我希望通过 seq 属性急切地加载和排序所选的 Attribute 。我已经尝试了各种HQL和Criteria查询,但似乎无法弄明白。

有帮助吗?

解决方案

此查询将返回所有具有必需属性的ProductType,并且会急切加载这些属性:

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 }

其他提示

或者,您可以通过在多方域中实现Comparable Interface并在单侧(而不是默认Set)中注入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)
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top