开发者

Grails gorm query question

开发者 https://www.devze.com 2023-03-15 04:38 出处:网络
having the domain classes: class A { Date dateCreated static hasMany = [b:B] ... } class B { String name String value

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:

  • A's creation date
  • B's value for A with the name entry set to 'X'

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

Thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号