Search code examples
javahibernatejpajpql

What is the return type for JPA query method when query result is not a class?


I have this query in JPA:

@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object> top10ProgramsOfTherapies();

It works great, but it returns a list of Objects, and I can not get the data out of it. What return type should I use to read the result data?


Solution

  • This query will return a list of objects array: Object[] so you need to change your code like this:

    @Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
    List<Object[]> top10ProgramsOfTherapies();
    

    And for each item in the list : item[0] will hold the programID value and item[1] will hold the COUNT(id) value, and you should cast them to their respective types as they will be just objects.