0

I have a task entity, which holds all user's tasks in the company. so it is @ManytoOne relationship. (many tasks belongs to specific user)

I want to calculate the sum:

(task_sum_of_user1 - avg)^2 + (task_sum_of_user2 - avg)^2 + .... (task_sum_of_user_N - avg)^2

I tested a query in Postgresql database and this one works:

select sum(v.t_sum) from(select (s.user_tasks + 10)^2 t_sum from (select count(*) user_tasks from Task t GROUP BY t.employee_id) s) v

But when I run the query in @Query annotation it doesn't seems to work:

@Query("select sum(v.t_sum) from(select (s.user_tasks + 10)^2 t_sum from (select count(*) user_tasks from Task t GROUP BY t.employee_id) s) v
")

it throws exception "unexpected token: (" What am I missing?

1
  • 2
    Why not create this as native query? e.g. @Query(value="YOUR_QUERY", nativeQuery=true) Commented Feb 27, 2019 at 17:30

1 Answer 1

1

You cannot use dbms's specific functions inside @Query, as it takes jpql as value. You can create a custom @Repository with native query, like that:

entityManager
    .createNativeQuery("select sum(v.t_sum) from(select (s.user_tasks + 10)^2 t_sum from (select count(*) user_tasks from Task t GROUP BY t.employee_id) s) v")
    .getSingleResult();

You need to map the result somehow or provide it as the second parameter of createNativeQuery.

As @Billy Frost noticed, adding nativeQuery flag as true to @Query is also an option.

Sign up to request clarification or add additional context in comments.

1 Comment

ah, yes, that is also an option;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.