Hibernate 标准和行数限制

发布于 2024-09-04 01:19:32 字数 589 浏览 7 评论 0原文

我有两个名为父级子级的实体,以一对多关系链接。 Child 实体有一个布尔值 isStudent 属性。

如何使用 Hibernate Criteria API 获取至少有一个 isStudent = true 子级的所有父级实体?

我试图使用 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));

谢谢你的帮助

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空城仅有旧梦在 2024-09-11 01:19:32

这对我有用:

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));

[编辑:修复了@brabenetz指出的错误]

父级和子级之间存在双向关系,即子级有一个字段“parent”
它返回拥有 >0 个孩子的父母。

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.

弄潮 2024-09-11 01:19:32

RobAu 的答案几乎就是我们所需要的。
但其中有一个小错误:您需要 Subqueries.lt(...),而不是 Subqueries.gt(..)

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文