xain
xain

Reputation: 13839

Grails gorm query question

having the domain classes:

class A {

 Date dateCreated
 static hasMany = [b:B]
 ...

}

class B {

  String name
  String value
...

}

What createCriteria or HQL query can I use to return a list with:

Note: Although there's no explicit constraint, there's only one "value" for each 'X' and a combination.

Thanks

Upvotes: 1

Views: 270

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75671

The HQL would be

def results = A.executeQuery(
    'select a.id, a.dateCreated, b from A a inner join a.b b ' +
    'where b.name=:name',
    [name: 'X'])

This will give you a List of 3-element Object[] arrays containing A.id, A.dateCreated, and the list of B instances. I added the id to the query so you can group by it client-side:

def grouped = results.groupBy { it[0] }

This will be a Map where the keys are the A ids and the values are the Lists from the original results.

Ideally you'd do the grouping at the database, but it would complicate the query, and assuming you don't have a large number of results it should be fast.

Upvotes: 2

Related Questions