grails首先找到

时间:2010-06-07 08:14:13

标签: grails

我知道这是一个简单的问题,但需要更多时间

如何从grails中的表中查找第一条记录。

我需要在不知道身份证号码的情况下获得第一条记录。

有没有像find这样的方法:先用grails?

提前感谢。

5 个答案:

答案 0 :(得分:14)

更新到Grails 2.1.1或更高版本为GORM添加了两个新方法(第一个和最后一个)来解决这个所需的功能。

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

答案 1 :(得分:4)

嗯,你必须通过什么衡量标准来定义这条记录应该是“第一个”。

假设您的意思是具有最早创建时间戳的记录,最简单且最强大的方法是向您的域类添加dateCreated属性,然后查询具有最低此类日期的实体。事实上,您甚至不必手动设置创建日期,因为Grails会为您执行此操作(只要您将属性命名为dateCreated) - 请参阅Grails文档中的Automatic timestamping

HQL查询类似于:

def firstObject = YourClass.find("FROM YourClass ORDER BY dateCreated")

答案 2 :(得分:2)

查看休眠标准和预测,例如:

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

答案 3 :(得分:1)

如果时间戳无关紧要,你可以尝试Daniel没有ORDER BY的答案,即

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

答案 4 :(得分:0)

您可以使用grails findBy方法返回查询的第一个结果。

- >来自1.3.7 docs

  

findBy *

     

目的

     

使用域类属性允许的动态方法   创建返回第一个的Grails查询方法表达式   查询结果

- >来自latest docs

  

findBy *目的

     

使用域类的属性执行的动态方法   返回第一个匹配结果的查询。