Đinh Hồng Châu
Đinh Hồng Châu

Reputation: 5430

Get first element in Grails list

How can I get the first element in Grails list of object return from command .list(), but not use Java method. I means that do we have any option to select the top element when call .list(), similar to the SQL query SELECT TOP FROM .

I don't like using this:

List domains = Domain.list()
return domains.get(0)

Becayse it causes memory resources so much. Thank you so much!

Upvotes: 1

Views: 9956

Answers (3)

doelleri
doelleri

Reputation: 19682

As of Grails 2.1.1, first() and last() methods have been added.

def firstResult = Domain.first()

and

def lastResult = Domain.last()

Upvotes: 2

Ted Naleid
Ted Naleid

Reputation: 26791

Another way to do it is with find, which returns the first result, or null if the table is empty.

User.find("from User")

If you want more than one, you can also use findAll with a max parameter

User.findAll("from User", [max: 10])

If you truly want just any object from the table, then list is probably your best bet, but most of the time, with these kinds of queries, you want to constrain it a bit more than that and going to HQL can make that very easy.

Upvotes: 1

tim_yates
tim_yates

Reputation: 171074

A quick way is to use the max parameter with list

Domain.list([max:1])

Or you could use a Criteria query I believe:

def domainCriteria = Domain.createCriteria()
def firstDomain = domainCriteria.list{
    maxResults( 1 )
    order( 'id', 'asc' )
}[0]

Upvotes: 11

Related Questions