简体   繁体   English

如何从 Spring 数据 JPA GROUP BY 查询返回对象列表而不是对象数组

[英]How to return a List of Objects instead of Array of Objects from a Spring Data JPA GROUP BY query

My question is related to this thread .我的问题与此线程有关。

Following is my repository method using group by some field:以下是我使用按某个字段分组的存储库方法:

@Query(value = "SELECT  t.test_id AS testId, COUNT(t.id) AS total FROM test_instances t GROUP BY t.test_id", nativeQuery = true)
public Object[] getTestStats();

It's working and the result is obtained as follows:它正在工作,结果如下:

[ [ 1, 2 ], [ 2, 1 ], [ 3, 2 ], [ 5, 1 ], [ 7, 2 ], [ 8, 1 ], [ 9, 1 ] ]

But, when I replace return type of getTestStats() from Object[] to List<?> I am getting the following error message:但是,当我将 getTestStats() 的返回类型从Object[]替换为List<?>时,我收到以下错误消息:

{
"cause": null,
"message": "Couldn't find PersistentEntity for type class [Ljava.lang.Object;!"]
}

I want to use List<?> because if it is working, I want to use custom projection to cast it to ie, List<CustomProjection>我想使用List<?>因为如果它正在工作,我想使用自定义投影将其投射到即List<CustomProjection>

I tried following return types {List<?>, List<CustomProjection>, CustomProjection[]} ;我尝试了以下返回类型{List<?>, List<CustomProjection>, CustomProjection[]} but every thing is returning the same error.但每件事都返回相同的错误。 Hope someone will help me, thanks in advance.希望有人能帮助我,在此先感谢。

If you want to return a List then:如果你想返回一个列表,那么:

  1. create a constructor which hold this fiels创建一个保存此字段的构造函数
  2. in your query you can create an Object which took this fields.在您的查询中,您可以创建一个采用此字段的 Object。

For example:例如:

 Select new com.CustomObject(t.test_id, COUNT(t.id))

And in this case you can use List<CustomObject> instead of an array of objects在这种情况下,您可以使用List<CustomObject>而不是对象数组

暂无
暂无

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

相关问题 如何创建Spring Data JPA查询,该查询将返回与相同类型的对象列表中的3个参数匹配的对象 - How to create a Spring Data JPA query that will return objects matching 3 parameters from a list of objects of the same type Spring Data JPA:查询如何返回非实体对象或对象列表? - Spring Data JPA: How can Query return Non- Entities Objects or List of Objects? Spring JPA Query从连接表返回对象列表和计数 - Spring JPA Query to return List of objects and count from join table 如何从 Spring Data JPA GROUP BY 查询返回自定义对象 - How to return a custom object from a Spring Data JPA GROUP BY query 使用“Spring Data Jpa 查询”检索“休眠代理对象”列表 - Retrieve List of "hibernate proxy objects" with "Spring Data Jpa query" Spring Data JPA-按ID绑定对象 - Spring Data JPA - Bind by Id instead objects Spring 数据 JPA 按对象列表查找 - Spring Data JPA Find By List of Objects 如何从具有多个计数和 Group by 查询的 Spring Data JPA 返回可分页的自定义对象? - How to return a pageable custom object from a Spring Data JPA with multiple counts and Group by query? 如何在 JPA 查询中返回页面而不是列表 - How to return Page instead of List on a JPA query JPA / HIBERNATE:查询如何返回非实体对象或带有内部非实体对象的对象列表? - JPA/HIBERNATE: How can Query return Non- Entities Objects or List of Objects with inner non-Entities objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM