Search code examples
springhibernatespring-dataspring-data-jpa

Using distinct in Spring data over multiple columns


My domain model is like this:

CollectedData {
  String name;
  String description;
  int count;
  int xAxis,
  int yAxis
}

Using Spring data repository query, I would like to retrieve all the unique rows (unique with name, xAxis, yAxis)

I am trying something like this

@Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
List<CollectedData> findAllDistinctData();

So, when I do

List<CollectedData> records= findAllDistinctData();
for (CollectedData record : records) { //Exception on this line
 }

Exception [Ljava.lang.Object; cannot be cast to CollectedData.

Is there any other way to write query for this ?


Solution

  • @Query return ArrayList of Object(s) instead of specific type of object. so you have to define some thing like

    @Query("select distinct a.name, a.xAxis, a.yAxis from CollectedData a")
    List<Object> findAllDistinctData();
    

    then cast according to your requirement,

    List<Object> cdataList=findAllDistinctData();
    for (Object cdata:cdataList) {
       Object[] obj= (Object[]) cdata;
         String name = (String)obj[0];
        String description = (String)obj[1];;
     ...
      }