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
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.
You can use hql to just return the fields you need
Book.executeQuery( "select b.id from Book b" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With