【问题标题】:Spring data native query with pageable SQL grammar error带有可分页 SQL 语法错误的 Spring 数据本机查询
【发布时间】:2021-09-23 07:50:56
【问题描述】:

我正在尝试在 spring-data 2.5.0 和 PostgreSQL 数据库上使用带有原生 SQL 和可分页的 spring 数据。

@Query(value = "SELECT dense_rank() OVER (ORDER BY rank DESC)," +
        "t.id, " +
        "FROM table t WHERE t.x > 0 ",
        nativeQuery = true)
Page<Object[]> getT(Pageable pageable);

但是我得到了一个 SQLException。结果 SQL 是

SELECT dense_rank() OVER (ORDER BY rank DESC),t.id FROM table t WHERE t.x > 0 , t.y desc limit 20

在其清晰可见的错误之处,spring-data 不会将 ORDER BY 子句添加到 SQL 中,可能是因为 dense_rank() 存在 ORDER BY 子句。如果我删除那个密集的选择,一切都会正常。

有没有可能使用 spring-data 来实现这个用例?也许一些可能的解决方法?我想使用整个 Pageable 对象(所以页面大小、偏移量和排序)

【问题讨论】:

  • 而不是 Page 尝试 Page
  • @AjayKumar 感谢您的回复,但事实并非如此,并没有解决问题

标签: sql spring postgresql spring-data


【解决方案1】:

经过长时间的尝试和寻找答案,我找到了解决方案,更有可能是解决方法。 在查询末尾添加 ORDER BY 1 将导致 spring-data 将 , order_column ASC/DESC LIMIT X OFFSET Y 放在 ORDER BY 1 之后(无论如何都不会修改结果)。

所以结果应该是

@Query(value = "SELECT dense_rank() OVER (ORDER BY rank DESC)," +
        "t.id, " +
        "FROM table t WHERE t.x > 0 ORDER BY 1",
        nativeQuery = true)
Page<Object[]> getT(Pageable pageable);

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2018-12-12
    • 2015-11-09
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多