|
Count Projection
The following example shows how to use Hibernate count aggregate projection.
Refer first example for the configuration and mapping.
|
package com.bethecoder.tutorials.hibernate.basic.criteria;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Property;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class CriteriaPropCntProjRestrictionTest {
/**
* @param args
*/
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Company.class);
criteria.setProjection(Property.forName("name").count());
Integer avgEmpCnt = (Integer) criteria.uniqueResult();
System.out.println("Total companies : " + avgEmpCnt);
session.getTransaction().commit();
session.close();
}
}
|
| |
It gives the following output,
Total companies : 10
|
|