Entity Map3
The following example shows creating an entity map from a projection list with aggregate values.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.criteria;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.transform.Transformers;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class CriteriaMapTest2 {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
Criteria criteria = session.createCriteria ( Company. class ) ;
criteria.setProjection ( Projections.projectionList ()
.add ( Property.forName ( "name" ) .count () .as ( "company_count" ))
.add ( Property.forName ( "employeeCount" ) .avg () .as ( "avg_employees" ) )
.add ( Property.forName ( "projectCount" ) .max () .as ( "max_project_count" ) )
) ;
criteria.setResultTransformer ( Transformers.ALIAS_TO_ENTITY_MAP ) ;
Map stats = ( Map ) criteria.uniqueResult () ;
System.out.println ( stats ) ;
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
{max_project_count=8478, avg_employees=40294.4, company_count=10}