Reputation: 505
I'm using java 8 and spring-data-rest to create API on my data.
I have a table Car(id, name, date...)
I'm trying to have an endpoint to retrieve distinct car names.
here's my Repository :
@RepositoryRestResource(path = "cars")
public interface CarRepository extends JpaRepository<Car, Long> {
//What i want to do
//@Query(value = "select distinct c.name as name from Car c")
@Query(value = "select distinct c from Car c")
List<Car> findDistinctName();
}
The query commented does not work , i have an exception
java.lang.IllegalArgumentException: PersistentEntity must not be null!
apparently this is the normal behavior of SDR.
I tried another solution by using Projections
@Projection(name = "name", types = {Car.class})
public interface CarName {
String getName();
}
but i cant get the distinct values, any idea?
Thank you :)
Upvotes: 1
Views: 1525
Reputation: 142
I think you should remove the @Query annotation.
Just
List<Car> findDistinctName();
or List<Car> findNameDistinct();
should suffice.
It will automatically generate the query select c.name from Car c
Upvotes: 0
Reputation: 505
I found an (ugly) workaround, using jpql :
@Query(value = "select c from Car C WHERE c.id IN (SELECT min(ca.id) FROM Car ca Group by ca.name)")
Upvotes: 0
Reputation: 30289
All you need, to do if you need a distinct list of cars, is such this query method:
public interface CarRepository extends JpaRepository<Car, Long> {
List<Car> findDistinctBy();
}
Spring Data JPA supports the Distinct keyword in repository query methods to set a distinct flag on the query to be created.
Upvotes: 1