首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Hibernate选择groupProperty,rowCount,rowCount > n?

Hibernate选择groupProperty,rowCount,rowCount > n?
EN

Stack Overflow用户
提问于 2011-03-24 08:31:20
回答 1查看 2.6K关注 0票数 1

很抱歉,如果这是一个愚蠢的问题,但是我已经花了一个下午的时间来解决这个问题,但是由于我不熟悉复杂的SQL,所以无法找到解决方案:

我想找到"Top消息发送用户从一个表中发送msg发送的计数>阈值“,这是我的标准:

代码语言:javascript
复制
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低于某些阈值”。如何用标准来实现它?非常感谢!

谢谢,我试过了。我现在可以使用子查询来实现我的目标,但是生成的查询是而不是那么聪明的!请参阅生成的SQL:

代码语言:javascript
复制
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查询:

代码语言:javascript
复制
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似乎要容易得多,但我对标准方法很好奇)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-24 13:49:14

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

代码语言:javascript
复制
    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 <您的主要条件,因此您需要使用别名createCriteria(MEssage.class, "alias")创建这些条件

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5416540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档