Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails find first

Tags:

grails

I know this is simple question but taking more time

How to find first record from table in grails .

I need to get only the first record with out knowing the id number .

Is there any method like find :first in grails ?

thanks in advance .

like image 320
srinath Avatar asked Jun 07 '10 08:06

srinath


3 Answers

Updating to Grails 2.1.1 or later adds two new methods (first and last) for GORM to address this needed feature.

From the docs:

class Person {
    String firstName
    String lastName
    Integer age
}

// retrieve the first person ordered by the identifier
def p = Person.first()
// retrieve the first person ordered by the lastName property
p = Person.first(sort: 'lastName')

// retrieve the first person ordered by the lastName property
p = Person.first('lastName')
like image 97
arcdegree Avatar answered Sep 18 '22 21:09

arcdegree


Well, you have to define by what measure this record is supposed to be the "first".

Assuming that you mean the record with the earliest creation timestamp, the easiest and most robust approach would be to add a dateCreated property to your domain class and then querying for the entity with the lowest such date. In fact you don't even have to set the creation date manually, because Grails does this for you (as long as you name the property dateCreated) - see Automatic timestamping in the Grails Documentation.

The HQL query would be something like:

def firstObject = YourClass.find("FROM YourClass ORDER BY dateCreated")
like image 22
Daniel Rinser Avatar answered Sep 21 '22 21:09

Daniel Rinser


Check out hibernate criteria and projections, e.g:

def location = Location.createCriteria()
def firstRecord = location.list{
    maxResults(1)
    order("id","asc")//assuming auto increment just to make sure 
}[0]

http://grails.org/doc/1.0.3/ref/Domain%20Classes/createCriteria.html

like image 23
z.eljayyo Avatar answered Sep 17 '22 21:09

z.eljayyo