Hibernate Criteria Query Example

The Restriction ClassThe Restrictions class is a static factory for Criterion instances. 

Find a Employee by name with Equal

Criteria criteria = session.createCriteria(Employee.class); 
criteria .add( Restrictions.eq("name", "David") );

Find a Employees by name with Matchmode:
Criteria criteria = session.createCriteria(Employee.class);

criteria.add(Restrictions.like("name", "David", MatchMode.START));

criteria.add(Restrictions.or(Restrictions.gt("Sal", new Long(10500)), 
 Restrictions.like("name", "jack", MatchMode.ANYWHERE)));


Order Class: The addOrder method can be used to order the results. The Order class has two static methods, asc and desc, which apply 
ascending or descending ordering constraints using a specified 
property as an input argument.

public Criteria addOrder(Order order); 

List emps = session.createCriteria(Employee.class) 
 .addOrder( Order.asc("lastName") ) 
 .list();


The Projections Class: Projections come from the 
org.hibernate.criterion.Projections factory class
Criteria crit = s.createCriteria(Employee.class); 
crit.setProjection( Projections.rowCount() ); 
List results = crit.list();

More than one projection can be applied to a criteria instance. To add multiple projections, the Projections class has a method called projectionList that returns an instance of the ProjectionList class.
Criteria criteria = session.createCriteria(PaymentModelImpl.class);
ProjectionList projectionList = Projections.projectionList();

projectionList.add(Projections.rowCount(), "count");
projectionList.add(Projections.sum("amount"), "totalAmount"); 
projectionList.add(Projections.groupProperty("customer"),"cust");
//Set the prijectionList obj into criteria object
criteria.setProjection(projectionList);

criteria.setResultTransformer(
Transformers.aliasToBean(CustomerPaymentInfo.class)); 
Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email