简体   繁体   中英

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:

{
"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>

I tried following return types {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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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