Wednesday, 20 April 2016

How to use Criteria API ?



Criteria is a simplified API for retrieving entities by composing Criterion objects.

This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

Example : Select employee data whose name starts with 'a' and Address is 'Boston'
List employees = session.createCriteria(Employee.class)
                       .add( Restrictions.like("name", "a%") )
                       .add( Restrictions.like("address", "Boston"))
                       .addOrder( Order.asc("name") )
                       .list();


Example : Select person names from Agra having age more than 60 in order of Name


Crietria c = session.createCriteria(Person.class);
c.add( Restrictions.like("city","AGRA") );
c.add( Restrictions.gt("age",60) );
c.addOrder( Order.asc("name") );
c.setProjection( Projections.property("name") );
List result = c.list();



Set Multiple projections at a time
ProjectionList p1 = Projections.projectionList();
p1.add( Projections.property("name") );
p1.add( Projections.property("address") );
c.setProjection(p1);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.