在@Query JPA Postgresql中使用WITH子句

时间:2018-03-14 22:12:10

标签: java postgresql jpa spring-boot

我正在尝试使用此处的查询 - 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子句?

1 个答案:

答案 0 :(得分:3)

在注释中使用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代码似乎是一个糟糕的想法。也许你应该使用存储过程或函数或其他。