在@Query JPA Postgresql中使用WITH子句

nir*_*air 4 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
Run Code Online (Sandbox Code Playgroud)

当我将其放入时@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
Run Code Online (Sandbox Code Playgroud)

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

Vas*_*san 7

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);
Run Code Online (Sandbox Code Playgroud)

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