问题
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