Search code examples
grailsgrails-orm

Grails best way to iterate all ids of a domain class


I have code like this:

Book.list().each {
  // real code actually does something more useful
  println "My id is " + it.id
}

It strikes me as a bit of a waste that the entire object of each Book is being loaded just to access the id. There is a load() method in Grails for when you only want to operate on the ID and I'm wondering if there's an equivalent here for loading all the domain instances? Should I use HQL? Or should I just leave it as-is?

PS: It makes me wonder whether there should be a option available to most GORM methods (finders etc) which cause it to only "load" instead of "get" the target class


Solution

  • You can use hql to just return the fields you need

    Book.executeQuery( "select b.id from Book b" );