Domanda

Ho i seguenti oggetti di dominio Grails

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

class Attribute {

    Boolean mandatory = false
    Integer seq

    static belongsTo = [productType: ProductType]
}

Vorrei ottenere tutti i ProductType e i loro Attribute obbligatori. Inoltre, vorrei che Attribute s fosse caricato e ordinato con entusiasmo dalla proprietà seq . Ho provato tutti i tipi di query HQL e Criteria, ma non riesco a capirlo.

È stato utile?

Soluzione

Questa query restituirà tutti i ProductTypes che hanno attributi obbligatori, con quegli attributi caricati avidamente:

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

Gli attributi sono in set mappati, quindi non è possibile ordinare, ma è abbastanza facile raccoglierli e ordinarli:

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

Altri suggerimenti

In alternativa, puoi ottenere un elenco ordinato dei molti lati implementando un'interfaccia comparabile nel dominio dei molti lati e iniettando SortedSet nel lato singolo (anziché nel set predefinito).

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)
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top