I am facing a problem with using HQL and aggregate functions to generate report output in HQL. As shown in the SQL below, I am using a nested select in the FROM clause mainly due to the fact that I needed to use the CASE keyword to break the amount field into the necessary reporting buckets. From that query, the outside query performs the aggregate reporting functionality.
Code:
SELECT
CATEGORY_ID,
SITE_LOCATION_ID,
SUM(TOTAL_AMOUNT),
SUM(TOTAL_APPROVED),
SUM(TOTAL_SUBMITTED),
SUM(TOTAL_DENIED)
FROM (
SELECT
d.categoryId as CATEGORY_ID,
d.siteLocationId as SITE_LOCATION_ID,
d.amount as TOTAL_AMOUNT,
CASE WHEN d.status = 'APPROVED' THEN d.amount ELSE 0 END AS TOTAL_APPROVED,
CASE WHEN d.status = 'SUBMITTED' THEN d.amount ELSE 0 END AS TOTAL_SUBMITTED,
CASE WHEN d.status = 'DENIED' THEN d.amount ELSE 0 END AS TOTAL_DENIED
FROM Document as d
WHERE /* insert subcriteria */
)
GROUP BY CATEGORY_ID, SITE_LOCATION_ID
When I tried to use this I got a syntax error with the '(' following the FROM and could never get this type of query to actually execute properly. My hope was that if it worked, I could use a ResultTransformer to populate a non-entity bean with the data. I had even hoped I could do this via the Criteria API but couldn't find a solution.
Alternative #2 was to go to the database and actually create a VIEW based on the actual document table that does the internal CASE logic and breaks the amount out for the reporting aggregate functions to use, but now I would be faced with using Native SQL as this VIEW isn't defined as an entity, nor would I want it to be unless I am able to configure the entity to be a "view" and create it as a view based on a SELECT statement call in annotations.
Is there not a way to easily do this via HQL and createQuery() or using the Criteria API?
If not, is there a better approach than create the view manually and using native SQL to populate a non-entity bean?