开发者

Hibernate select groupProperty , rowCount with rowCount > n?

开发者 https://www.devze.com 2023-02-19 23:46 出处:网络
Sorry if it is a dumb question but I\'ve stuck with this problem for a whole afternoon but cannot find a solution because I\'m not skilled with complicated SQL :

Sorry if it is a dumb question but I've stuck with this problem for a whole afternoon but cannot find a solution because I'm not skilled with complicated SQL :

I want to find "Top n mes开发者_如何学运维sage-sending users from a table with msg sent count > threshold" , this is my criteria :

Criteria c = session.createCriteria(Message.class);
ProjectionList plist = Projections.projectionList();
plist.add(Projections.groupProperty("user"));
plist.add(Projections.rowCount() , "count");
c.setProjection(plist);
c.addOrder(Order.desc("count"));

c.setFirstResult(0);
c.setMaxResults(count);

This is what I can write , but it lacks of "filtering rows with rowCount lower than some threshold". How to implement it with criteria ? Thanks a lot !

-------------- updated ------------------------

Thanks @TheStijn , I tried . I now can use subquery to achieve my goal , but the generated query is not so clever ! See the generated SQL :

select
    this_.fromUser as y0_,
    count(*) as y1_ 
from
    Message this_ 
where
    this_.fromUser is not null 
    and this_.created>? 
    and this_.created<? 
    and ? <= (
        select
            count(*) as y0_ 
        from
            Message msg_ 
        where
            msg_.fromUser=this_.fromUser 
            and msg_.fromUser is not null 
            and msg_.created>? 
            and msg_.created<?
    ) 
group by
    this_.fromUser 
order by
    y1_ desc limit ?

That is , the subquery repeats most of the main query , which I think it is a little redundant . Is there any criteria that builds such SQL queries :

select
    this_.fromUser as y0_,
    count(*) as y1_ 
from
    Message this_ 
where
    this_.fromUser is not null 
    and this_.created>? 
    and this_.created<? 
    and y1_ > ? // threshold
group by
    this_.fromUser 
order by
    y1_ desc limit ?

Thanks a lot !

(It seems much easier to use HQL to do this , but I am curious about the Criteria way)


You'll need an additional subquery like:

    DetachedCriteria subQuery = DetachedCriteria.forClass(Message.class, "msg");
    subQuery.add(Restrictions.eqProperty("msg.user", "mainQuerymsg.user"));
    subQueryEntriesCount.setProjection(Projections.rowCount());

    c.add(Subqueries.lt(1L, subQuery));

mainQuerymsg < your main criteria so you'ill need to create these criteria with an alias createCriteria(MEssage.class, "alias")

0

精彩评论

暂无评论...
验证码 换一张
取 消