java 休眠条件和行数限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2972879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:46:23  来源:igfitidea点击:

Hibernate Criteria and row count restriction

javahibernatecriteriasubquery

提问by Mark

i have two entities named Parentand Child, linked in a one-to-manyrelationship. The Child entity has a boolean isStudentproperty.

我有两个名为ParentChild 的实体,它们以一对多的关系链接。Child 实体具有布尔isStudent属性。

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

我如何使用 Hibernate Criteria API 获得至少有一个 Child 的所有 Parent 实体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):

我试图使用 Projection 对象来计算所有至少有一个 Child 属性设置正确的父对象,然后返回那些行数大于零的父对象,就像下面的一段代码(这不起作用) , 尽管):

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

谢谢你的帮助

回答by RobAu

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]

[编辑:修复了@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.

Parent 和Child 之间存在双向关系的地方,即Child 有一个字段“parent”,它返回有>0 个孩子的Parent。

回答by brabenetz

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(...)

RobAu 的回答几乎就是我们所需要的。但是它有一个小错误:而不是子查询。gt(..) 你需要子查询。(……)

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