tags:

views:

43

answers:

3

How to use "SELECT id, name, part, description FROM user " in grails findAll tag.

I tried

 User.findAll("SELECT id, name, part, description FROM user") 

instead using

User.findAll("FROM user")

But shows errors . can anyone suggest me the tag

thanks, sri..

+2  A: 

finadAll() returns a Collection of domain objects, so enumerating columns to select does not make sense; the queries it understands are not real SQL, and consist basically only of WHERE clauses. Since you don't seem to want to constrain the result set, this is probably all you need:

User.findAll()

It will return a collection of all User objects. If you need constraints, the syntax ist

User.findAll("from User as u where u.id=?", [userId])

Or, even simpler, you can use a dynamic finder:

User.findAllById(userId);
Michael Borgwardt
@Michael, but do we have any tag which shows "SELECT id, name, part, description FROM user" . thanks
Srinath
@Srinath: no, there is nothign like that. It would not make sense for a framework that works with domain objects. What's wrong with using the methods I listed to get User objects and then accessing the properties of those objects? It sounds like you've worked only with PHP before and are now trying to write PHP code in Grails. That won't get you far.
Michael Borgwardt
@Michael, Previously i worked in Ruby on Rails. I already used the tag findAll you mentioned above. I just want to know is there any tags like that in Grails too. thanks for your suggestions :(
Srinath
@Srinath: You can use groovy.sql.Sql to do direct SQL queries, but in doing so, you're leaving the Grails framework. BTW, you keep saying "tag", but we're talking about methods here, not tags.
Michael Borgwardt
@Michael, yeah. I used groovy.sql.Sql for previous application, it will return results in array. But for this app i used findAll . I posted to know and share some info from you people if there are any miscellaneous methods in grails . thanks
Srinath
+1  A: 

If you want to run report-style queries like this, use the executeQuery method:

def rows = User.executeQuery("SELECT id, name, part, description FROM User")

The return value will be a List of Object[] where each element in the object array is the type of the column, i.e. the 1st element will be a long, 2nd a String, etc.

Note that User has to be capitalized since you're referring to the Hibernate entity - this isn't a SQL query, it's HQL.

Burt Beckwith
@Burt, yeah thanks.
Srinath
A: 

If you want to query for only certain fields, you can use a criteria query with a projection.

Example:

def userProperties = User.withCriteria {
    projections {
        property('id')
        property('name')
        property('part')
        property('description')
    }
}

This query will return an array of Strings (or whatever the database column type is mapped to) for each matching row, instead of a domain object.

ataylor