Hibernate Tutorials/
« Previous | 1 | 2 | 3 | Next »
You can use add() method available for Criteria object to add restriction for a criteria query. Following is the example to add a restriction to return the records with salary is equal to 2000:

Criteria cr =session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary",2000));
List results =cr.list();

Following are the few more examples covering different scenarios and can be used as per requirement:

Criteria cr =session.createCriteria(Employee.class);

// To get records having salary more than 2000
cr.add(Restrictions.gt("salary",2000));

// To get records having salary less than 2000
cr.add(Restrictions.lt("salary",2000));

// To get records having fistName starting with zara
cr.add(Restrictions.like("firstName","zara%"));

// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName","zara%"));

// To get records having salary in between 1000 and 2000
cr.add(Restrictions.between("salary",1000,2000));

// To check if the given property is null
cr.add(Restrictions.isNull("salary"));

// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"))

// To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));

// To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));

You can create AND or OR conditions using LogicalExpression restrictions as follows:

Criteria cr =session.createCriteria(Employee.class);

Criterion salary =Restrictions.gt("salary",2000);
Criterion name =Restrictions.ilike("firstNname","zara%");

// To get records matching with OR condistions
LogicalExpression orExp =Restrictions.or(salary, name);
cr.add( orExp );


// To get records matching with AND condistions
LogicalExpression andExp =Restrictions.and(salary, name);
cr.add( andExp );

List results =cr.list();

Though all the above conditions can be used directly with HQL as explained in previous tutorial.
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com