[an error occurred while processing this directive]

Criteria Query Examples

                         

In the last lesson we learnt how to use Criteria Query to select all the records from Insurance table. In this lesson we will learn how to restrict the results returned from the database. Different method provided by Criteria interface can be used with the help of Restrictions to restrict the records fetched from database.


 

 

 

Criteria Interface provides the following methods:

Method Description
add The Add method adds a Criterion to constrain the results to be retrieved.
addOrder Add an Order to the result set.
createAlias Join an association, assigning an alias to the joined entity
createCriteria This method is used to create a new Criteria, "rooted" at the associated entity.
setFetchSize This method is used to set a fetch size for the underlying JDBC query.
setFirstResult This method is used to set the first result to be retrieved.
setMaxResults This method is used to set a limit upon the number of objects to be retrieved.
uniqueResult
          
This method is used to instruct the Hibernate to fetch and return the unique records from database.

Class Restriction provides built-in criterion via static factory methods. Important methods of the Restriction class are:

Method Description
Restriction.allEq
          
This is used to apply an "equals" constraint to each property in the key set of a Map
Restriction.between
          
This is used to apply a "between" constraint to the named property
Restriction.eq
          
This is used to apply an "equal" constraint to the named property
Restriction.ge
          
This is used to apply a "greater than or equal" constraint to the named property
Restriction.gt
          
This is used to apply a "greater than" constraint to the named property
Restriction.idEq This is used to apply an "equal" constraint to the identifier property
Restriction.ilike
          
This is case-insensitive "like", similar to Postgres ilike operator
Restriction.in This is used to apply an "in" constraint to the named property
Restriction.isNotNull This is used to apply an "is not null" constraint to the named property
Restriction.isNull           This is used to apply an "is null" constraint to the named property
Restriction.le          This is used to apply a "less than or equal" constraint to the named property
Restriction.like This is used to apply a "like" constraint to the named property
Restriction.lt This is used to apply a "less than" constraint to the named property
Restriction.ltProperty This is used to apply a "less than" constraint to two properties
Restriction.ne          This is used to apply a "not equal" constraint to the named property
Restriction.neProperty This is used to apply a "not equal" constraint to two properties
Restriction.not   This returns the negation of an expression
Restriction.or  This returns the disjuction of two expressions

Here is an example code that shows how to use Restrictions.like method and restrict the maximum rows returned by query by setting the Criteria.setMaxResults() value to 5.

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
 @author Deepak Kumar
 
 * http://www.roseindia.net 
Hibernate Criteria Query Example

 *  
 */public class HibernateCriteriaQueryExample2 {
  public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read 
hibernate.cfg.xml and prepare hibernate for

      // use
      SessionFactory sessionFactory
 = 
new Configuration().configure()
          .buildSessionFactory();
      session = 
sessionFactory.openSession
();
      //Criteria Query Example
      Criteria crit = 
session.createCriteria
(Insurance.class);
      crit.add(Restrictions.like("
insuranceName"
"%a%"))//Like condition
      crit.setMaxResults(5)//
Restricts the max rows to 5


      List insurances = crit.list();
      for(Iterator it = 
insurances.iterator
();it.hasNext();){
        Insurance insurance =
 
(Insuranceit.next();
        System.out.println("
ID: " 
+ insurance.getLngInsuranceId());
        System.out.println("
Name: " 
+ insurance.getInsuranceName());
        
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }    
  }
}

                         

Ask programming questions?

 

 

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

12 comments so far (post your own) View All Comments Latest 10 Comments:

What a great site with tons of info. I'll be sure to be back.

Posted by Amazed Guy on Sunday, 06.28.09 @ 19:38pm | #88867

      View This Comment Separately

I need help ....how we can union two queries using criteria.

Posted by srikanth on Saturday, 12.6.08 @ 03:53am | #82462

      View This Comment Separately

Hi,

Please suggest the Hibernate examples. We will develop the code examples.

Thanks
Deepak Kumar

Posted by Deepak on Tuesday, 06.3.08 @ 21:18pm | #61983

      View This Comment Separately

Hi,

The site is very good to learn Hibernate Basics.Its better to have few more examples with detailed explanation of each.

Posted by Sandeep on Tuesday, 06.3.08 @ 11:21am | #61922

      View This Comment Separately

Good tutorial to learn basics of Hibernate. It can't help much to learn detailed concepts of Hibernate.

Posted by Tids on Friday, 03.28.08 @ 11:03am | #54554

      View This Comment Separately

It is the best site to know clearly the programming on hibernate

Posted by saroj on Wednesday, 02.20.08 @ 13:41pm | #49192

      View This Comment Separately

Hello everyone,

I'm new to hibernate-struts so i want to ask question.

How to display data using hibernate struts without using criteria?

thanks

Posted by Ehsan on Thursday, 10.4.07 @ 13:59pm | #31359

      View This Comment Separately

session.close() should be in finally block

Posted by friend on Thursday, 03.8.07 @ 00:29am | #11049

      View This Comment Separately

there are so many good examples of hibernate queries but there is no any example of "how to use stored procedures with hibernate".
Thanks

Posted by sweta gupta on Wednesday, 01.31.07 @ 11:16am | #4844

      View This Comment Separately

Good! I appreciate the example, but should have tried to implement all possible methods as much as possible in the above example.

Posted by Balapani on Wednesday, 01.31.07 @ 04:23am | #4785

      View This Comment Separately
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name

 

 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright 2007. All rights reserved.

[an error occurred while processing this directive]