【问题标题】:Hibernate select groupProperty , rowCount with rowCount > n?休眠选择 groupProperty , rowCount with rowCount > n?
【发布时间】:2011-03-24 08:31:20
【问题描述】:

对不起,如果这是一个愚蠢的问题,但我已经为这个问题困扰了整个下午但找不到解决方案,因为我不熟悉复杂的 SQL:

我想从一个表中找到“前 n 个消息发送用户,msg sent count > threshold”,这是我的标准:

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

这是我能写的,但它缺乏“过滤行数低于某个阈值的行”。如何用标准来实施它?非常感谢!

------------- 已更新 ------------

谢谢@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方式很好奇)

【问题讨论】:

    标签: hibernate criteria detachedcriteria


    【解决方案1】:

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

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

    创建这些标准

    【讨论】:

    • 嗨,我试过了,但得到了一个“不太聪明”的 SQL 查询。请你再看一遍好吗?谢谢。
    • 你不能在hibernate中做一些在sql中做不到的事情。由于您不能在 sql 的 where 子句中使用聚合变量(至少在我知道的任何数据库中都不能使用聚合变量),因此您将无法在 hibernate 中使用它)。如果您上面的 sql 正在运行,请告诉我您正在使用哪个数据库。
    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2011-11-18
    • 2012-09-18
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多