Hibernate Criteria

The Hibernate facilitate Criteria interface to fetch records based on specific criteria.

Methods of Criteria interface

  • public Criteria add(Criterion c) : This method is used to restrictions.
  • public Criteria addOrder(Order o):¬†This method is used to order records either ASC or DESC
  • public Criteria setFirstResult(int offset): This method is used to set the offset from where the records to be fetched.
  • public Criteria setMaxResult(int max): This method is used to set the max number of records to be fetched.
  • public List list(): It returns list containing objects as result.
  • public Criteria setProjection(Projection projection): It is used to set the Projection.

Restrictions class

Restrictions class provides static methods that can be used as Criterion.

Example to fetch all records

 
Crietria c=session.createCriteria(Product.class);
List list = c.list(); 

Example to fetch to first 10 records

Crietria c=session.createCriteria(Product.class);
c.setFirstResult(0);  
c.setMaxResult(10); 
List list = c.list();

Example to fetch products whose price qty greater than 10

Crietria c=session.createCriteria(Product.class);
//Here qty is property of Product Persistent class
c.add(Restrictions.gt("qty",10));  
List list = c.list();

Example to order records in ascending order by price

 Crietria c=session.createCriteria(Product.class);  
 c.addOrder(Order.asc("price"));  
 List list=c.list();  

Example with Projection to fetch price and qty columns only

Projections class in used to fetch certain columns from a relation or table.

Criteria c=session.createCriteria(Product.class);  
c.setProjection(Projections.projectionList()
               .add( Projections.property("price"))
               .add( Projections.property("qty"))
             );  
List list=c.list(); 

Leave a Reply