开发者

Hibernate Criteria and row count restriction

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


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 a bug a pointed out by @brabenetz]

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.


The Answer from RobAu is nearly what we needed. But there is a small bug in it: Instead of Subqueries.gt(..) you need Subqueries.lt(...)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜