[英]Count rows in the result of a query in Hibernate
I'm facing the following problem: 我面临以下问题:
Criteria criteria = getSession().createCriteria(User.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id"));
projectionList.add(Projections.countDistinct("friend_id"));
projectionList.add(Projections.property("registrationDate"));
projectionList.add(Projections.property("lastLoginDate"));
criteria.setProjection(projectionList);
this piece of code returns me a couple of entries with the data I require. 这段代码为我返回了一些我需要的数据条目。 However, I need the rowcount for it.
但是,我需要它的行数。 Is there a clean way of doing this, rather than just doing a:
有没有一种干净的方法可以做到这一点,而不仅仅是:
return criteria.list().size();
? ?
Criteria criteria = session.createCriteria(Track.class)
.setProjection(Projections.rowCount());
List result = criteria.list();
if (!result.isEmpty()) {
Integer rowCount = (Integer) result.get(0);
System.out.println("Total records: " + rowCount);
What if you add this to the end of the ProjectionList? 如果将此添加到ProjectionList的末尾怎么办?
Projections.rowCount()
I use the following code to search something and then get the rowcount for it. 我使用以下代码搜索某些内容,然后获取其行数。
Criteria criteria = session.createCriteria(LogEntryOracle.class);
if (search != null && !search.isEmpty()) {
criteria.add(Restrictions.ilike("xml", search, MatchMode.ANYWHERE));
}
criteria.setProjection(Projections.rowCount());
return (Number) criteria.uniqueResult();
Seems that my problem was caused by the lack of analysis: 似乎我的问题是由于缺乏分析引起的:
Criteria criteria = getSession().createCriteria(User.class);
criteria.setProjection(Projections.countDistinct("id"));
return (Long) criteria.uniqueResult();
since we're already grouping by the user ID then all I had to do is find the amount if unique user IDs matching the search criteria. 因为我们已经按用户ID进行了分组,所以我所要做的就是找到与搜索条件匹配的唯一用户ID的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.