質問

次のGrailsドメインオブジェクトがあります

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

class Attribute {

    Boolean mandatory = false
    Integer seq

    static belongsTo = [productType: ProductType]
}

すべての ProductType およびそれらの必須の Attribute を取得したい。さらに、選択した Attribute seq プロパティで積極的にロードおよびソートしたいです。あらゆる種類のHQLおよびCriteriaクエリを試しましたが、理解できないようです。

役に立ちましたか?

解決

このクエリは、必須属性を持つすべての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 }

他のヒント

別の方法として、多サイドドメインに比較可能なインターフェイスを実装し、(デフォルトセットの代わりに)片側に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