views:

351

answers:

2

Hi,

i have two entities named Parent and Child, linked in a one-to-many relationship. The Child entity has a boolean isStudent property.

How do i get, using the Hibernate Criteria API, all the Parent entities that have at least one Child with isStudent = true?

I was trying to use a Projection object to count all the parents that have at least one Child with the property correctly set, and then return those whose row count is greater than zero, like in the following piece of code (which doesn't work, though):

Criteria criteria = getCurrentSession().createCriteria(Parent.class);

criteria.setProjection(Projections.alias(Projections.rowCount(), "count"))
.add(Restrictions.gt("count", 0)).createCriteria("children")
.add(Restrictions.eq("isStudent", true));

Thanks for your help

A: 

Check if this helps http://stackoverflow.com/questions/2941962/hibernate-criteria-for-elements-inside-a-set/2947067#2947067

Reddy
The post is about Criteria aliases, my question is about the usage of Projections in the case I've described.
Marco
A: 

This worked for me:

            DetachedCriteria crit = DetachedCriteria.forClass( Parent.class, "theparent" );
            DetachedCriteria countSubquery = DetachedCriteria.forClass(Child.class, "child");
            countSubquery.add( Property.forName("theparent.id").eqProperty( "parent.id" ))
                         .setProjection(Projections.count("id"));
            crit.add(Subqueries.gt(Long.valueOf(0), countSubquery));

Where there is a bidirectional relation between Parent and Child, i.e. the Child has a field "parent" It returns the Parents that have >0 children.

RobAu