I have a project using Spring Data JPA that consumes data from a table full of addresses. One of the columns of this table is the city. I would like to get a distinct list of cities that are in the table i.e. SELECT DISTINCT city FROM address
.
Is there a way to do this using Spring Data JPA?
Manish's comment should probably be bumped up to an answer (which i'll try to capture here since it ultimately solved my problem...although projections didn't seem to work with
select distinct
). The selected answer works in spring-data-jpa, but fails in spring-data-rest. One possible workaround for the spring-data-rest scenario is to create a separate@RestController
for theselect distinct
resultsperhaps there's a similar but more elegant variation based on @RepositoryRestController
I have a similar problem with Spring Data Rest.
Both methods works with spring-data and I can use it in Spring Services, but via REST endpoint only the first method works:
The 2nd method returns an mapping error:
It works with an POJO object but not if the object is in a collection. Is this a bug in spring-data-rest, that it works with objects but not with collections.
Spring-Boot 2.0.4.Release Spring-Data: 2.1.0.RC1 Spring-Data-Rest: 3.1.0.RC1
This can be achieved using a
@Query
annotation as:Then, a call to
addressRepository.findDistinctCity()
would return the distinct city names.A sample application is available on Github for review. Run integration test as
mvn clean test
to verify the approach.