Detached Criteria Max
The following example shows how to use Hibernate Detached Criteria.
It returns companies having maximum number of projects.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.criteria;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class DetachedCriteriaMaxTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
DetachedCriteria maxProjCnt =
DetachedCriteria.forClass ( Company. class )
.setProjection ( Projections.max ( "projectCount" )) ;
Criteria criteria = session.createCriteria ( Company. class ) ;
criteria.add ( Property.forName ( "projectCount" ) .eq ( maxProjCnt )) ;
List<Company> companies = criteria.list () ;
System.out.println ( "Selected row count : " + companies.size ()) ;
for ( Company company : companies ) {
System.out.println ( company ) ;
}
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
Selected row count : 1
{ id = 6, name = RNK, employeeCount = 98890,
projectCount = 8478, address1 = add1412, address2 = add27823 }