Mohan
Mohan

Reputation: 1244

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 i.e., 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.

Upvotes: 2

Views: 3276

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

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

Upvotes: 2

Related Questions