简体   繁体   English

使用休眠条件计数where子句

[英]count in where clause using hibernate criteria

I have simple model of project with users. 我与用户有一个简单的项目模型。 Suppose I need to select all the projects that have for example minimum of 5 users. 假设我需要选择所有具有至少5个用户的项目。 In sql it would be something like this (I haven't tried it, might be mistake somewhere): 在SQL中将是这样的(我还没有尝试过,可能在某处是错误的):

select * from PROJECTS p where count(select * from USERS u left join PROJECT_MEMBERS m on u.object_id=m.user_id where m.project_id=p.object_id)>5;

In project model I have: 在项目模型中,我有:

private Set<UserModel> users = new HashSet<UserModel>();

and its mapped like that: 及其映射如下:

<set name="users" 
    cascade="none"
    table="PROJECT_MEMBERS">
    <key column="project_id" />
    <many-to-many 
        column="user_id" 
        class="UserModelImpl"/>
</set>

Currently my dao looks like that: 目前我的岛看起来像这样:

Criteria hbCriteria = session.createCriteria(ProjectModelImpl.class);
hbCriteria.add(Restrictions.ilike("name", criteria.getProjectName(), MatchMode.ANYWHERE));
return hbCriteria.list();

How can I add create criterion that would select only those projects that have criteria.getMinUsers() users? 如何添加仅选择具有criteria.getMinUsers()用户的项目的创建条件?

Let me know if you need any more code or mapping 让我知道是否需要更多代码或映射

应该这样做:

.add(Restrictions.sizeGe("users", criteria.getMinUsers()))

The solution of Vlad is definitely better than this one. 弗拉德的解决方案肯定比这更好。 I let it here anyway to show you how Subqueries can be used. 无论如何,我在这里告诉您如何使用子查询。

Use a subquery: 使用子查询:

Criteria hbCriteria = session.createCriteria(ProjectModelImpl.class, "project");
hbCriteria.add(Restrictions.ilike("project.name", criteria.getProjectName(), MatchMode.ANYWHERE));

DetachedCriteria count = DetachedCriteria.forClass("ProjectModelImpl.class", "project2");
count.createAlias("project2.users", "member");
count.add(Restrictions.eq("project2.id", "project.id");
count.setProjection(Projections.count("member.id");

hbCriteria.add(Subqueries.le(5, count));
return hbCriteria.list();

use a detachedCritera first 首先使用detachedCritera

DetachedCriteria countOfUsers = DetachedCriteria.forClass("ProjectModelImpl.class", "proj");
countOfUsers .createAlias("proj.users", "member");
countOfUsers .setProjection(proj.count("member.id");

use a alias on that property and then use that alias to create a restriction on it. 在该属性上使用别名,然后使用该别名对其创建限制。

Criteria hbCriteria = session.createCriteria(ProjectModelImpl.class) 
hbCriteria.add(Restrictions.ilike("name", criteria.getProjectName(), MatchMode.ANYWHERE))
.add(Subqueries.ge(5,countOfUsers));
return hbCriteria.list();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM