Is it possible to use COUNT with a DISTINCT JPA projection?

Viewed 29158

I am using a JPA distinct projection to get some data:

select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...

This works fine with setFirstResult and setMaxResults to page data.

However I need to count the total number of rows without fetching all of them. I have tried:

select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...

This does not work (with EclipseLink anyway) and it doesn't seem to be allowed by the JPA spec. Is there another way? I don't want to have to write an SQL query to do this.

4 Answers

Though this answer is coming late but it might help future people. In your repository. This worked for me in my own case.

@Query("SELECT DISTINCT COUNT(o.f1, o.f2...) FROM SomeEntity o WHERE....)

Hope it helps others.

Related