Mark Buikema
Mark Buikema

Reputation: 2540

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?

Upvotes: 2

Views: 8344

Answers (2)

Adrian
Adrian

Reputation: 3134

You can also create a DTO class, for example, TherapyDto which will have a constructor with 2 parameters and use it this way:

@Query("SELECT new com.my.TherapyDto(programId,COUNT(id)) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<TherapyDto> top10ProgramsOfTherapies();

Upvotes: 4

cнŝdk
cнŝdk

Reputation: 32145

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.

Upvotes: 2

Related Questions