【问题标题】:using WITH clause in @Query JPA Postgresql在@Query JPA Postgresql 中使用 WITH 子句
【发布时间】:2018-08-23 14:44:12
【问题描述】:

我正在尝试从这里使用这个查询 - http://technoir.blog/blog/post/timeseries_tips_for_postgresql

with filled_dates as (
  select day, 0 as blank_count from
    generate_series('2014-01-01 00:00'::timestamptz, current_date::timestamptz, '1 day') 
      as day
),
signup_counts as (
  select date_trunc('day', created_at) as day, count(*) as signups
    from users
  group by date_trunc('day', created_at)
)
select filled_dates.day, 
       coalesce(signup_counts.signups, filled_dates.blank_count) as signups
  from filled_dates
    left outer join signup_counts on signup_counts.day = filled_dates.day
  order by filled_dates.day

当我把它放在@Query("WITH filled_dates as ( .... ") 中时,它会抛出这个错误 -

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: WITH near line 1, column 1 [WITH filled_dates as

如何在手动 JPA 查询中使用 WITH 子句?

【问题讨论】:

  • 您将查阅有关什么是 JPQL 的文档并意识到 SQL != JPQL,并且 Spring 有一些“nativeQuery”标志。但是你已经通过文档了,不是吗?

标签: java postgresql jpa spring-boot


【解决方案1】:

在注解中使用nativeQuery=true 切换到纯SQL。否则,它需要 JPQL 查询。

@Query(value = "WITH filled_dates AS ...", nativeQuery=true)

另外,请确保您在空格、引号等方面已为 Java 正确格式化。

如果要使用参数,请使用位置参数而不是命名参数。

例如(有点傻):

@Query(value="select * from emp where name=?1 and dept=?2", nativeQuery=true)
public Collection<Employee> findEmployeesByNameAndDept(String name, String dept);

不过,使用 JPA 向 Java 代码添加如此复杂的查询似乎是个糟糕的主意。也许你应该使用存储过程或函数或类似的东西。

【讨论】:

  • 我还不明白如何使用存储过程进行此类查询。你能帮我给出一个起点吗?
  • @nirvair 抱歉,我也不是该领域的专家。我的建议是提出一个以此为重点的新问题。不过,SO 可能不是最好的地方。在 codereview.stackexchange.com 上发布您当前的代码(带有大量 Java 查询),并询问如何改进它。同时,如果添加 nativeQuery 至少解决了错误,您可以接受此答案,以便对其他人有所帮助!
  • 还有一个查询。如何在此查询中添加参数?会和 JPQL 一样吗?
  • @nirvair 使用?1?2 等位置参数并在参数中保持相同的顺序。
  • 你能举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
  • 2020-04-28
相关资源
最近更新 更多