Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Projections and "Having" clause

I'm using NHibernate to query my database with the criteria API. My criteria is below:

ICriteria c = Session.CreateCriteria(typeof(Transaction));

ProjectionList projections = Projections.ProjectionList();
projections.Add(Projections.Sum("Units"), "Units");
projections.Add(Projections.GroupProperty("Account"), "Account");
projections.Add(Projections.GroupProperty("Security"), "Security");
c.SetProjection(projections);

This is working fine, but what I would like is a way to be able to limit the query to only return when the "Units" property is > 0. In SQL I would simply us a Having Units > 0 clause however I haven't been able to find a way to do this in NHibernate. Does anyone have any ideas or is my only option to use HQL?

like image 523
lomaxx Avatar asked Mar 12 '09 00:03

lomaxx


2 Answers

You can access the ProjectionCriteria from the Criteria object.

...
c.SetProjection(projections)
.ProjectionCriteria
.Add(Restrictions.Ge("Units", 0));

EDIT: This solution doesn't currently work, however it should work in NHibernate 2.1.0

like image 183
Stuart Childs Avatar answered Sep 23 '22 10:09

Stuart Childs


For whomever drops by here with a similar problem, I just solved it this way:

IProjection howMany = Projections.Count("Id").As("HowMany");

ICriteria criteria = session
    .CreateCriteria<L10N>()
    .SetProjection(
        howMany,
        Projections.GroupProperty("Native"),
        Projections.GroupProperty("Locale")
    );

criteria.Add(Restrictions.Gt(howMany,1));
like image 28
ANeves Avatar answered Sep 23 '22 10:09

ANeves