计算满足特定条件的对象数

时间:2010-12-30 00:27:08

标签: java hibernate

标题并不能说明完整的故事。请阅读信息。

我有两个对象:成人和儿童。 Child有一个布尔字段isMale,以及对Adult的引用。成人不参考儿童。

public class Adult {
   long id;
}
public class Child {
   long id;
   boolean isMale;
   Adult parent;
}

我想创建一个查询,列出每个成年人的儿子数量,包括没有儿子的成年人。我试过了:

查询1

SELECT adult, COUNT(child) FROM Child child 
RIGHT OUTER JOIN child.parent as adult 
WHERE child.isMale='true' 
GROUP BY adult

转换为sql

select
    adult.id as col_0_0_,
    count(child.id) as col_1_0_,
    ... {omit properties}
from
    Child child
right outer join
    Adult adult
        on child.parentId=adult.id 
where
    child.isMale = 'true'
group by
    adult.id

查询1不会选择没有任何儿子的成年人。

查询2:

SELECT adult, COUNT(child.isMale) FROM Child child 
RIGHT OUTER JOIN child.parent as adult 
GROUP BY adult

转换为sql:

select
    adult.id as col_0_0_,
    count(child.id) as col_1_0_,
    ... {omit properties}
from
    Child child
right outer join
    Adult adult
        on child.parentId=adult.id 
group by
    adult.id

查询2没有正确的儿子数。基本上COUNT不评估isMale 查询1中的where子句过滤掉了没有儿子的成人。

如何为此用例构建HQL或Criteria查询?

感谢。

1 个答案:

答案 0 :(得分:1)

对于没有孩子的成年人,条件child.isMale='true'为假(isMaleNULL),因此您应该处理此案例:

SELECT adult, COUNT(child) 
FROM Child child RIGHT OUTER JOIN child.parent as adult 
WHERE child IS NULL OR child.isMale='true'  
GROUP BY adult