7

Suppose I have the following Domain class:

class Book {
  String title
  String author
  byte[] largeCoverArtImage
}

I have a list view where I do not need to display largeCoverArtImage, how can I perform the following SQL query using GORM Criteria?

select title, author from Book
Stephen Swensen
  • 22,107
  • 9
  • 81
  • 136

2 Answers2

7

You can run HQL queries that select individual columns with executeQuery:

def titlesAndAuthors = Book.executeQuery('select title, author from Book')

This will return a List of Object[], e.g.

for (row in titlesAndAuthors) {
   String title = row[0]
   String author = row[1]
   ...
}
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • Not the answer I was hoping for, since I can't use the standard Criteria pagination pattern with executeQuery. But marked as accepted answer (i.e. "No"). I will point out that a solution that does work with Critiera, is to create a db View and separate Domain class (assuming legacy db) specifically for the list page (thereby easily leveraging the Criteria pagination pattern). Of course, the downside is that then you have two incompatible classes representing essentially the same set of records. – Stephen Swensen Aug 22 '10 at 13:28
7

In Grails (tested with 1.3.7 version) you can write:

def titlesAndAuthors = Book.withCriteria {
        projections {
            property 'title', 'title'
            property 'author', 'author'
        }
}

And you'll get a list of Object[] like above example.

Manuel Vio
  • 506
  • 3
  • 6
  • Cool - good to know, we are running grails 1.3.2 right now, and in maintenance mode, but if I ever get the opportunity to upgrade and try this out, I'll come back and let you know how it worked out. – Stephen Swensen May 17 '11 at 14:23
  • 2
    Flash forward: I'm on a project using Grails 2.0.3 now and this works well! – Stephen Swensen Dec 08 '12 at 03:47
  • Is there a way to get a list of Object{} instead of list of Object[]? using "projections" breaks my api because I rely on having lists of objects. It does retrieve a list of Object[] though. Thanks for the suggestion. – Calicoder Apr 12 '17 at 23:11