在grails中获取最后两条记录的有效方法?

efficient way to get last two records in grails?

我有一个域class说

class Content{

  String content
  Date dateCreated
  Date lastUpdated

}

数据库中的内容记录很少。我想检索最新的两条记录。在 Grails 中查询两条最新记录的有效方法是什么?谢谢!

不是

Content.list(max: 2, sort: "dateCreated", order: "desc")

有可能吗?

您可以将 HQL 查询写为 -

String queryString = "select content from Content order by lastUpdated desc"

List contentList = Content.executeQuery(queryString,[max: 2, offset: 0])

无论您做出 "weapon" 的选择...

HQL查询

def query = "SELECT content from Content order by lastUpdated desc"
def data = Content.executeQuery(query,[max: 2, offset: 0])

SQL查询

SELECT * FROM table_name ORDER BY lastUpdated DESC LIMIT 2

Grails createCriteria:

def c = Content.createCriteria()
def results = c.list {
    order("lastUpdated", "desc")
    maxResults(2)
}

...最佳选择的主要原则保持不变 - 降序排列并获得 2 个结果
如果要检索的数据是如此微不足道,则不需要实际的 SQL 或 HQL 查询。您可以使用 Grails 功能,它不会在性能上留下任何痕迹。