Get children count via HQL

Posted by Thomas Lötzer on Stack Overflow See other posts from Stack Overflow or by Thomas Lötzer
Published on 2010-01-29T11:03:20Z Indexed on 2010/06/12 12:43 UTC
Read the original article Hit count: 393

Filed under:
|
|
|

Hi,

I have a one-to-many mapping between a parent entity and child entities. Now I need to find the number of children associated with each parent for a list of parents. I am trying to do this with HQL but I am not sure how I can get the list of parents in there. Also, I don't know how I can return the entity itself and not just its ID. My current HQL query is:

select new map(parent.id as parentId, count(*) as childCount) 
from Parent parent left join parent.children children
group by parent.id

but this only returns the ID and does not filter on specific parents.

EDIT Based on Pascal's answer I have modified the query to

select new map(parent as parent, count(elements(parent.children)) as childCount) 
from Parent parent
group by parent

That does work, but is prohibitively slow: 30 seconds instead of 400 ms on the same database.

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate