Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 669
Fletch Avatar asked Jan 10 '12 09:01

Fletch


2 Answers

A criteria query in combination with a projection solves your problem when you want to avoid using HQL.

    def criteria = Book.createCriteria()
    def result = criteria.list {
        projections {
            property 'id'
        }
    }

The Hibernate SQL logging shows that only the IDs are loaded from the database, and not the entire Books: select this_.id as y0_ from book this_.

The criteria query can also be added as a named query on the Book domain class, providing easy access to the list of IDs.

like image 62
Ruben Avatar answered Oct 14 '22 18:10

Ruben


You can use hql to just return the fields you need

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

like image 45
Tomas Lin Avatar answered Oct 14 '22 17:10

Tomas Lin