View RSS Feed

My Java Tips

Criteria instance

Rate this Entry
by , 06-02-2011 at 07:22 PM (2395 Views)
Hibernate provides an interface org.hibernate.Criteria, which represents a query against a particular persistent class.

Review the following example:

Java Code:
Criteria crit = session.createCriteria(Student.class);
crit.setMaxResults(50);
List students = crit.list();
Resultset can be narrowed according to requirement. The class org.hibernate.criterion.Restrictions defines factory methods for obtaining certain built-in Criterion types.

Java Code:
List students = sess.createCriteria(Student.class)
.add( Restrictions.like("name", "Laiq%") )
.add( Restrictions.between("age", minAge, maxAge) )
.list();
Below, I will show how Restrictions may be grouped logically.

Java Code:
List students = sess.createCriteria(Student.class)
.add( Restrictions.like("name", "Laiq%") )
.add( Restrictions.or(
Restrictions.eq( "age", new Integer(0) ),
Restrictions.isNull("age")
) )
.list();
Java Code:
List Students = sess.createCriteria(Student.class)
.add( Restrictions.in( "name", new String[] { "Laiq", "Izi", "Pk" } ) )
.add( Restrictions.disjunction()
.add( Restrictions.isNull("age") )
.add( Restrictions.eq("age", new Integer(20) ) )
.add( Restrictions.eq("age", new Integer(21) ) )
.add( Restrictions.eq("age", new Integer(22) ) )
) )
.list();
There are many built-in criterion types (Restrictions subclasses), but one that is especially useful lets you specify SQL directly.

Java Code:
List students = sess.createCriteria(Student.class)
.add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Laiq%", Hibernate.STRING) .list();
Hope this helps.

Submit "Criteria instance" to Facebook Submit "Criteria instance" to Digg Submit "Criteria instance" to del.icio.us Submit "Criteria instance" to StumbleUpon Submit "Criteria instance" to Google

Categories
Hibernate

Comments