Criteria Queries
The interface org.hibernate.Criteria represents a query against a particular persistent class.
The Session is a factory for Criteria instances.
Criteria : Select * from Employee.
Criteria criemp = session.createCriteria(Employee.class);
List emplist = criemp.list();
Restrictions to narrow result set
The class org.hibernate.criterion.Restrictions used to narrow result set.
// SELECT * FROM EMPLOYEE WHERE AGE=24; ----SQL COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class).add( Restrictions.eq("age", new Integer(24) ) ).list();
// Not Equal in hibernate criteria
// SELECT * FROM EMPLOYEE WHERE AGE !=24; ----SQL COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class).add( Restrictions.ne("age", new Integer(24) ) ).list();
Ordering the results
// SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY EMP_NAME DESC; ----SQL COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class).
add( Restrictions.eq("age", new Integer(24) ) ).addOrder( Order.desc("empname") ).list();
Associations
// SELECT e.name FROM EMPLOYEE e , address a where e.address_id=a.address_id and a.country='US'; ----SQL COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class).createAlias("address","add").
add( Restrictions.eq("add.country", "US" ) ).list();
Example queries
The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.
// SELECT * FROM EMPLOYEE e WHERE e.dept='IT'; ----SQL COMMAND
criteria query for above query is :
Employee emp = new Employee();
cat.setDept('IT');
List emplist = session.createCriteria(Employee.class)
.add( Example.create(emp) )
.list();