简体   繁体   中英

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. In sql it would be something like this (I haven't tried it, might be mistake somewhere):

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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