Criteria API example in Hibernate

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.

The following example shows how to work with Hibernate Criteria API.
Create MySQL Table

 

Insert some data into the items table

 

Create hibernate.cfg.xml and put under classpath

 

Create hibernate domain object for items

 

Create HibernateUtil.java class which gives SessionFactory instance

 

Now below one by one snippets show how to work with Criteria

Create a Criteria instance and retrieve the result

 

If you want to limit max result then you can do so using setMaxResult(int max) method.

 

So the above code returns maximum number of four items if there are more than four items.

You can perform Like search using below query

 

You can restrict the fetched values using Restriction.between()

 

Ordering the results either by ascending or descending

 

You can also do the same thing in the following way

 

How to restrict the results by equality check

 

Testing the Criteria API

 

Output

 

For more information you can look at http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querycriteria.html

Thanks for your reading. Please leave a comment because comment helps us to improve.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.