简体   繁体   English

查询结果不是类时,JPA查询方法的返回类型是什么?

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

I have this query in JPA: 我在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? 我应该使用哪种返回类型来读取结果数据?

You can also create a DTO class, for example, TherapyDto which will have a constructor with 2 parameters and use it this way: 您还可以创建一个DTO类,例如TherapyDto ,它将具有一个带有2个参数的构造函数,并以这种方式使用它:

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

This query will return a list of objects array: Object[] so you need to change your code like this: 该查询将返回一个对象数组列表: Object[]因此您需要像这样更改代码:

@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 object s. 对于列表中的每个itemitem[0]将保存programID值, item[1]将保存COUNT(id)值,并且您应将它们programID为它们各自的类型,因为它们将只是object s。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM