【问题标题】:LIMIT in Postgres not supported in HQL?HQL 不支持 Postgres 中的 LIMIT?
【发布时间】:2011-05-04 22:08:39
【问题描述】:

我在执行 HQL 的 Grails 中使用以下代码获取前 30 个 Item 对象时出错:

 def items = Item.executeQuery('SELECT i FROM Item as i LIMIT 30 OFFSET 0')

我的后端数据库是 Postgres。但是,我得到了:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: LIMIT near line 1, column ...

显然,该错误表明 HQL 不支持 LIMIT。我如何使它工作?也就是说,如何让 HQL 执行 Postgres 很好支持的原生 SQL?

【问题讨论】:

    标签: hibernate grails hql


    【解决方案1】:
    query.setMaxResults(..)
    

    看看hibernate API

    【讨论】:

      【解决方案2】:

      Grails/GORM way using list 也可以

      def items = Item.list(offset:0, max:30)
      

      由于您使用的是 HQL,因此我根据以下评论编辑了我的答案;两种方法都行

      def items = Item.executeQuery('SELECT i FROM Item as i', [max: 30, offset: 0]) 
      

      【讨论】:

      • 在我们讨论 executeQuery 方法时,最好使用 [max: 30, offset: 0] 映射作为参数。 Item.executeQuery('SELECT i FROM Item as i', [max: 30, offset: 0])
      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2010-09-21
      • 2013-01-18
      • 2023-04-04
      相关资源
      最近更新 更多