简体   繁体   中英

using WITH clause in @Query JPA Postgresql

I am trying to use this query from here - 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

When I put this in @Query("WITH filled_dates as ( .... ") , it throws this error -

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

How can I use WITH clause in manual JPA queries?

Use nativeQuery=true in the annotation to switch to plain SQL. Otherwise it expects JPQL queries.

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

Also, make sure you've formatted it correctly for Java in terms of spaces, quotes etc.

If you want to use parameters, use positional instead of named parameters.

For example (a bit silly):

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

Adding such a complex query to Java code using JPA seems like a poor idea though. Maybe you should use a stored procedure or function or somesuch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM