srinath
srinath

Reputation: 399

grails find first

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 .

Upvotes: 11

Views: 13071

Answers (5)

chim
chim

Reputation: 8573

You can use the grails findBy methods to return the first result of a query.

-> From the 1.3.7 docs

findBy*

Purpose

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return the first result of the query

-> from the latest docs

findBy* Purpose

Dynamic method that uses the properties of the domain class to execute a query returning the first matching result.

Upvotes: 0

arcdegree
arcdegree

Reputation: 2720

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')

Upvotes: 14

z.eljayyo
z.eljayyo

Reputation: 1289

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

Upvotes: 2

Jörg Brenninkmeyer
Jörg Brenninkmeyer

Reputation: 3344

If timestamp doesn't matter, you could try if Daniel's answer without ORDER BY works, i.e.

def firstObject = YourClass.find("FROM YourClass")

Upvotes: 1

Daniel Rinser
Daniel Rinser

Reputation: 8855

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")

Upvotes: 4

Related Questions