3

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.

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
  • 1
    What's the use of getting several numbers without any reference of what they correspond to? – Diego Mijelshon Oct 13 '10 at 00:03
  • the application which I am working on has an architecture which uses repositories for data access. There are predefined repositories to fetch objects.the objects thus fetched need to implement certain interfaces. Under such architecture I cannot retrieve an object the one returned by this criteria. – frictionlesspulley Oct 13 '10 at 00:28

2 Answers2

0

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"));
victorskl
  • 61
  • 1
  • 6
0

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.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154