Thursday, April 15, 2010

Fixing a GORM/HQL Group By Clause

I was just trying to use a "group by" clause with some Grails domain classes in HQL and ran across the following cryptic message:
"Not in aggregate function or group by clause."

My models looked a little like this:

class Account {
  String name
  static hasMany = [entries:Entry]
}

class Entry {
  Date entryDate
  double amount
  static belongsTo = [account:Account]
}

I wanted to get a balance of all the accounts and ran an HQL query something like this:

def results = Entry.executeQuery(
  'select ent.account, sum(ent.amount) ' +
  'from Entry as ent group by ent.account')

I found that the reason for the failure seems to be that Hibernate adds all the other fields of Account to the select clause of the SQL under the hood. Changing the HQL to this, solved my problem:

def results = Entry.executeQuery(
  'select ent.account.id, sum(ent.amount) ' +
  'from Entry as ent group by ent.account')