Using distinct in Spring data over multiple columns

17,814

@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];;
 ...
  }
Share:
17,814
White Roses
Author by

White Roses

Updated on June 30, 2022

Comments

  • White Roses
    White Roses almost 2 years

    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 ?