Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

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.

like image 839
David Tinker Avatar asked Oct 05 '10 08:10

David Tinker


People also ask

How does COUNT DISTINCT work?

The COUNT DISTINCT function returns the number of unique values in the column or expression, as the following example shows. SELECT COUNT (DISTINCT item_num) FROM items; If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL.

Does DISTINCT COUNT NULL values?

NULL values are not included in COUNT DISTINCT counts.

How to COUNT the number of unique values in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

What are JPA projections?

Projection is one of the first things you're probably thinking about when implementing a query with Spring Data JPA. This is because projection defines the entity attributes and the database columns returned by your query. So, selecting the right columns is important for your business logic.


1 Answers

Try this:

select count(distinct o) from SomeEntity o where ...
like image 99
Lars Høidahl Avatar answered Sep 23 '22 15:09

Lars Høidahl