Search code examples
nhibernatehibernatecriterianhibernate-criteria

Hibernate Criteria: Projecting Count with group by clause


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.


Solution

  • 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.