Hibernate选择groupProperty,rowCount用rowCount> N +

时间:2011-03-24 08:31:21

标签: hibernate criteria detachedcriteria

很抱歉,如果这是一个愚蠢的问题,但我已经坚持这个问题一整个下午,但找不到解决方案,因为我不熟悉复杂的SQL:

我想找到“从msg发送计数>阈值的表格中发送前3位消息的用户”,这是我的标准:

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

这是我可以编写的内容,但缺少“过滤行,其中rowCount低于某个阈值”。如何用标准来实现它?非常感谢!

--------------更新------------------------

谢谢@TheStijn,我试过了。我现在可以使用子查询来实现我的目标,但生成的查询不那么聪明!请参阅生成的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 ?

也就是说,子查询重复了大部分主要查询,我认为这有点多余。是否有任何构建此类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 y1_ > ? // threshold
group by
    this_.fromUser 
order by
    y1_ desc limit ?

非常感谢!

(使用HQL这样做似乎要容易得多,但我对Criteria方式感到好奇)

1 个答案:

答案 0 :(得分:2)

您需要一个额外的子查询,例如:

    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&lt;您的主要标准是,您需要使用别名createCriteria(MEssage.class, "alias")

创建这些条件