Hibernation criteria and row limit

I have two objects named Parent and Child , connected in a one-to-many relationship . The child object has a boolean property isStudent.

How can I get, using the Hibernate Criteria API, all parent objects that have at least one Child with isStudent = true?

I tried to use the Projection object to count all parents who have at least one Child with the property set correctly, and then return those whose number of lines is greater than zero, for example, in the following code fragment (which doesn’t work):

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 the help

+5
source share
2 answers

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.lt(Long.valueOf(0), countSubquery));

[Edit: fixed bug indicated by @brabenetz]

If there is a bi-directional relationship between the parent and the child, that is, the child has a "parent" field, He returns the parents who have> 0 children.

+9
source

The answer from RobAu is what we need. But there is a small mistake: instead of subqueries. gt (..) you need subqueries. lt (...)

crit.add(Subqueries.lt(Long.valueOf(0), countSubquery));
+1
source

All Articles