ChrisGeo
ChrisGeo

Reputation: 3907

JPQL Aggregation return

Lets say I have the following JPQL query

SELECT e.column1, e.column2, SUM(e.column3), SUM(e.column4) FROM Entity e GROUP BY e.column1, e.column2

Obviously I wont be returning an Entity object but something a bit more complex. How do I return this in the method?

public List<???> query1() {

   Query q = entityManager.createQuery("...");

   List<Something???> list = q.getResultList();

   return list;
}

Upvotes: 0

Views: 483

Answers (1)

JB Nizet
JB Nizet

Reputation: 691953

Such a query returns a List<Object[]>, where each element is thus an array of Objects. The first element of the array will have the type of Entity.column1, the second one will have the type of Entity.column2, and the last 2 ones will be (with Hibernate at least) of type Long (check with EclipseLink).

It's up to you to transform the List<Object[]> in a List<Foo>, by simply looping over the list of objects and transforming each one into a Foo. You may also use the constructor notation directly in the query (provided Foo has such a constructor), but I personally dislike it, because it isn't refactorable:

select new com.baz.bar.Foo(e.column1, e.column2, SUM(e.column3), SUM(e.column4)) from ...

Upvotes: 2

Related Questions