Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Subset of Columns with Gorm

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
like image 464
Stephen Swensen Avatar asked Jul 09 '10 02:07

Stephen Swensen


People also ask

How does Gorm know which table?

It uses the name of your type. Here the type is User so gorm will use the users table by default. You can also configure it to not use the plural form if you'd like.

Is Gorm slow?

One major concern when using gorm is that it runs very slowly when the traffic is high. There are some benchmarks on the internet which shows that gorm can runs 3-5 times slower than the standard library.

What is ORM in Golang?

Golang ORMs Luckily, the Go community has built a number of Object Relational Mapping libraries (ORMs) to allow Go developers to use JSON key:value pair syntax and encoding to map directly to a SQL database like PostgreSQL. ORMs enable developers to use their native programming paradigm to map data to SQL.


2 Answers

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]
   ...
}
like image 138
Burt Beckwith Avatar answered Sep 30 '22 13:09

Burt Beckwith


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.

like image 33
Manuel Vio Avatar answered Sep 30 '22 13:09

Manuel Vio