我有父/子关系:newsItem 1- * comment。
如何使用一个Criteria查询选择newsItems列表以及每个newsItem的注释计数?
我想做这样的事情:
select news_item.*, count(comment.id) from news_item left join comment on comment.news_item_id = news_item.id group by news_item.id
结果应该是List of Object [2] {newsItem,int}。
这可以通过Criteria查询完成吗?
谢谢!
答案 0 :(得分:3)
好吧,我找到了解决方案。希望它可以帮助某人:
Criteria criteria = session.createCriteria(NewsItem.class);
criteria.createAlias(NewsItem.COMMENTS, NewsItem.COMMENTS, Criteria.LEFT_JOIN);
ProjectionList properties = Projections.projectionList();
properties.add(Projections.groupProperty(NewsItem.ID).as(NewsItem.ID));
properties.add(Projections.property(NewsItem.DATE).as(NewsItem.DATE));
properties.add(Projections.property(NewsItem.NAME).as(NewsItem.NAME));
properties.add(Projections.property(NewsItem.PREVIEW).as(NewsItem.PREVIEW));
properties.add(Projections.property(NewsItem.IMAGE).as(NewsItem.IMAGE));
properties.add(Projections.count(NewsItem.COMMENTS + "." + Comment.ID).as(NewsItem.COMMENTS_COUNT));
criteria.setProjection(properties);
criteria.setResultTransformer(Transformers.aliasToBean(NewsItem.class));
您还应该向NewsItem类添加虚拟属性COMMENTS_COUNT(Long)。
答案 1 :(得分:1)
您可以使用以下内容:
Criteria criteria = session.createCriteria(NewsItem.class,"newItem")
.createAlias(NewsItem.COMMENTS, "comments", Criteria.LEFT_JOIN)
.setProjection(Projections.projectionList().add(
Projections.alias(Projections.count("comments.id"), "commentsCount")).add(
Projections.alias(Projections.groupProperty("newItem.id"), "newItem")))
.setResultTransformer(Transformers.aliasToBean(NewItemCommentsGroupBy.class));
确保NewItemCommentsGroupBy类是这样的:
class NewItemCommentsGroupBy{
long commentsCount;
NewsItem newsItem;
}