Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinct counting with Spring JPA Repository

How do I do a distinct counting with Spring Data JPA? I do not want to use the @Query annotation. The equivalent sql query would be:

SELECT COUNT(DISTINCT rack) FROM store WHERE id = 10001;

I tried by writing the following query, but it isn't working:

int countDistinctRackById();
like image 582
Benimo Avatar asked Jun 04 '18 11:06

Benimo


3 Answers

This should work :

Integer countDistinctRackById(Long id);
like image 84
Ilias Mentz Avatar answered Sep 18 '22 07:09

Ilias Mentz


I just tried this out and none of the existing answers work.

The following query:

Integer countDistinctRackById(String id);

Will render something like this:

select distinct count(table0_.rack) as col_0_0_ from table table0_ where table0_.id=?

As I am currently stuck with Spring Boot 1.2.3, idk if there were any changes later, but to achieve a count distinct I had to define a custom query:

@Query("Select count(distinct rack) from Table t where t.id = ?1")

like image 45
avolkmann Avatar answered Sep 17 '22 07:09

avolkmann


Try this according to Spring Documentation:

Integer countDistinctRackById(String id);

Replace the word Rack with the actual name of rack field

like image 43
Afridi Avatar answered Sep 20 '22 07:09

Afridi