Hibernate : Projections & Aggregations

The Criteria API provides the org.hibernate.criterion.Projections class which can be used to get average, maximum or minimum of the property values. The Projections class is similar to the Restrictions class in that it provides several static factory methods for obtaining Projectioninstances. The class org.hibernate.criterion.Projections is a factory for Projection instances.
You can apply a projection to a query by calling setProjection().

Criteria cr = session.createCriteria(Employee.class);

// To get total row count.

// To get average of a property.

// To get distinct count of a property.

// To get maximum of a property.

// To get minimum of a property.

// To get sum of a property.

List results = session.createCriteria(Cat.class)
    .setProjection( Projections.projectionList()
        .add( Projections.rowCount() )
        .add( Projections.avg("weight") )
        .add( Projections.max("weight") )
        .add( Projections.groupProperty("color") )

List results = session.createCriteria(Domestic.class, "cat")
    .createAlias("kittens", "kit")
    .setProjection( Projections.projectionList()
        .add( Projections.property("cat.name"), "catName" )
        .add( Projections.property("kit.name"), "kitName" )
    .addOrder( Order.asc("catName") )
    .addOrder( Order.asc("kitName") )


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s