GORM Hibernate query
Question
I have the following Grails domain objects
class ProductType {
String name
static hasMany = [attributes: Attribute]
}
class Attribute {
Boolean mandatory = false
Integer seq
static belongsTo = [productType: ProductType]
}
I would like to get all ProductType
s and their mandatory Attribute
s. Furthermore, I'd like the selected Attribute
s to be eagerly loaded and sorted by the seq
property. I've tried all kinds of HQL and Criteria queries, but can't seem to figure it out.
Solution
This query will return all ProductTypes that have mandatory attributes, with those attributes eagerly loaded:
def types = ProductType.executeQuery("""
select distinct type from ProductType type
left join fetch type.attributes attribute
where attribute.mandatory=true""")
The attributes are in mapped Sets, so there's no ordering, but it's easy enough to collect and sort them:
def sortedAttributes = types.collect { it.attributes }.flatten().sort { it.seq }
OTHER TIPS
Alternatively, you can get a sorted list of the many side by implementing a Comparable Interface in the many-side domain, and injecting SortedSet in the one-side (instead of the default Set).
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)
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow