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 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




For more information you can look at

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

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.