Narrowing the result set in the Hibernate by R4R Team

Every individual query criterion is an instance of the interface org.hibernate.criterion.Criterion.  The class org.hibernate.criterion.Restrictions  defines factory methods for obtaining certain built-in Criterion types.Restrictions can be grouped logically.

List student = session.createCriteria(Student.class)
    .add( Restrictions.like("name", "Gourav%") )
    .add( Restrictions.between("weight", minWeight, maxWeight) )
    .list();

List student  = session.createCriteria(Student.class).add( Restrictions.like("name", "Gourav%") ).add( Restrictions.or (Restrictions.eq( "age", new Integer(0) ), Restrictions.isNull("age") ) ).list();

List student = session.createCriteria(Student.class).add( Restrictions.in( "name", new String[] { "Gourav", "Pal", "Pk" } ) )
    .add( Restrictions.disjunction()
    .add( Restrictions.isNull("age") )
    .add( Restrictions.eq("age", new Integer(0) ) )
    .add( Restrictions.eq("age", new Integer(1) ) )
    .add( Restrictions.eq("age", new Integer(2) ) )
    ) ).list();

There are a range of built-in criterion types (Restrictions subclasses). One of the most useful allows you to specify SQL directly.The {alias} placeholder with be replaced by the row alias of the queried entity. You can also obtain a criterion from a Property instance.

List student = session.createCriteria(Student.class)
.add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Gourav%", Hibernate.STRING) ).list();

 
Now we can create a Property by calling Property.forName():

Property age = Property.forName("age");
List Student = session.createCriteria(Student.class)
.add( Restrictions.disjunction()
.add( age.isNull() )
.add( age.eq( new Integer(0) ) )
.add( age.eq( new Integer(1) ) ).add( age.eq( new Integer(2) ) ) ) )
 .add( Property.forName("name").in( new String[] { "Gourav", "Pal", "Pk" } ) ).list();
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!