简体   繁体   中英

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.

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"));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM