【发布时间】: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