如何从命令.list()返回Grails对象列表中的第一个元素,而不是使用Java方法。我的意思是,当调用.list()时,我们有没有选择top元素的选项,类似于SQL查询select TOP FROM。
我不喜欢用这个:
List domains = Domain.list()
return domains.get(0)因为它占用了大量的内存资源。非常感谢!
发布于 2011-04-01 15:57:11
一种快捷的方法是将max参数与list一起使用
Domain.list([max:1])或者,您可以使用我相信的条件查询:
def domainCriteria = Domain.createCriteria()
def firstDomain = domainCriteria.list{
maxResults( 1 )
order( 'id', 'asc' )
}[0]发布于 2014-07-24 23:56:49
发布于 2011-04-02 11:09:00
另一种方法是使用find,它返回第一个结果,如果表为空,则返回null。
User.find("from User")如果需要多个参数,也可以使用带有最大参数的findAll
User.findAll("from User", [max: 10])如果您真的只需要表中的任何对象,那么list可能是您最好的选择,但大多数情况下,对于这些类型的查询,您希望对其进行更多的约束,使用HQL可以使这一点变得非常容易。
https://stackoverflow.com/questions/5508915
复制相似问题