tags:

views:

89

answers:

2

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 .

+2  A: 

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")
Daniel Rinser
yeah.I need just to fetch the first record in db irrespective of any timestamp. because my timestamp will always change when edited . cant we get with out timestamp ?Thanks Daniel.
srinath
"because my timestamp will always change when edited" -> If you use Grails' automatic timestamping, there is a difference between `dateCreated` (set once upon insert and not changed thereafter) and `lastUpdated` (updated upon each update/change).
Daniel Rinser
If your id is numeric and auto incremented in strictly ascending order, you could of course just `ORDER BY id`
Daniel Rinser
thanks daniel ..
srinath
A: 

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

def firstObject = YourClass.find("FROM YourClass")
werner5471
I would rather not rely on the assumption, that this returns the object inserted first. AFAIK, this is an implementation detail of the DBMS and depending on the DBMS you use may not hold true. Same as with `SELECT * FROM xyz LIMIT 1` in plain SQL.
Daniel Rinser
As for MySQL, I just found this thread in the forum: http://forums.mysql.com/read.php?21,239471,239471 Conclusion: Due to the implementation of the engine, the default order MAY be the insert order (at least for MyISAM), but this is definitely nothing to rely on! I suppose the same holds for other DBMS.
Daniel Rinser