Hibernate Criteria: Projecting Count with group by clause

坚强是说给别人听的谎言 提交于 2020-01-04 02:39:33

问题


I want to execute the following SQL

select count(*) as myCount from user group by name;

I came up with the following criteria for the same

DetachedCriteria.ForClass(typeof(UserDTO))
    .setProjections(Projections.ProjectionList()
                        .Add(Projections.rowCount(),"myCount")
                        .Add(Projections.groupProperty("this.name"));

I get the result back as pair of the count and name,How can I get just the count from this.


回答1:


I don't think you can do it with Criteria, but it's easy with HQL. It's exactly the same string as your SQL query, but with entity/property names instead of table/column ones.




回答2:


You can use count distinct if there is only one group by column.

HQL:

select count(distinct name) as myCount from user

Criteria:

DetachedCriteria.ForClass(typeof(UserDTO))
.setProjections(Projections.ProjectionList()
                    .Add(Projections.countDistinct("name"),"myCount"));


来源:https://stackoverflow.com/questions/3919445/hibernate-criteria-projecting-count-with-group-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!