Using distinct in Spring data over multiple columns


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

@Query("select distinct, 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];;
White Roses
Author by

White Roses

Updated on June 30, 2022


  • White Roses
    White Roses over 1 year

    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.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 ?