Hello,
I am also trying to convert several queries to a single query using select new Object(args).
Previously, I retrieved a list of "Ccr" objects for viewing in a datatable on a JSF page. I then access the properties of these objects in each row of the table using syntax like #{ccr.property}. This works, but ends up requiring about five queries per row of the datatable when I could easily write it as one query for the whole table myself.
Here is the query I have come up with:
Code:
select new domain.removed.mud.helperentity.CcrListItem(ccrAuditFirst, ccrAuditLast, ccr)
from Ccr ccr
left join ccr.ccrAudits ccrAuditFirst
left join ccr.ccrAudits ccrAuditLast
where ccrAuditFirst.timeStamp = (
select min(ccrAudit_l.timeStamp) from CcrAudit ccrAudit_l
left join ccrAudit_l.ccr ccr_l
where ccr_l = ccr
)
and ccrAuditLast.timeStamp = (
select max(ccrAudit_l.timeStamp) from CcrAudit ccrAudit_l
left join ccrAudit_l.ccr ccr_l
where ccr_l = ccr
)
Each Ccr object has a collection called ccrAudits which contains CcrAudit objects. For each Ccr I would like to see the first and last CcrAudit, based on their timestamps. Sometimes the first and last might be the same.
However when this query is run, only the id fields for the three objects in the constructor of the new object are retrieved, and all other information is loaded after that in even more queries than before. I thought it might be that I am aliasing a collection (with one object in it) to a single object in the constructor, but hibernate doesn't seem to mind that and changing the query to a restricted cartesian product doesn't make any difference to the number of queries being run.
I also tried fetch joining as in the manual, but got the following error message:
Code:
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list...
Any suggestions would be greatly appreciated,
Dave