Criteria Queries Implementation – Hibernate

Criteria Queries Implementation – Hibernate
Hibernate provides org.hibernate.criteria interface to create Criteria Queries.

Consider an example, We have an entity class named “Employee”  then our criteria query will look like,

Criteria criteria = session.createCriteria(Employee.class);

Adding Restrictions:
To use condition-based criteria queries in hibernate application we need to add restrictions to the query. Here let us see some examples of adding restrictions to Hibernate Queries.

Before proceeding to example, let us see some of the standard Restrictions.

.add(Restrictions.eq(Propertyname, object value) – This will compare the property name equals to the object value

.add(Restrictions.gt(Propertyname, object value) – This will return the results when the value of that property is greater than the specified value

.add(Restrictions.lt(Propertyname, object value) – This will return the results when the value of that property is lesser than the specified value

.add(Restrictions.ge(Propertyname, object value) – This will return the results when the value of that property is greater than or equal to the specified value

.add(Restrictions.le(Propertyname, object value) – This will return the results when the value of that property is lesser than or equal to the specified value

.add(Restrictions.like(Propertyname, object value) – This will compare the propertywith specified pattern

.add(Restrictions.between(Propertyname, object low, object high) – This method compares the property within the range of low and high

Now let us see an example,

Structure
structure1

Lets create a table in Database for this example and enter some values,

table

hibernate.cfg.xml

hibernate.reveng.xml

NewHibernateUtil.java

CriteriaExample.java

CriteriaExample.hbm.xml

Controller.java


Output:

This is print the records that matches the city name Berlin

eq

Output 2:

Prints records which has money property value more than 15000

gt

Output 3:

Prints records which has money property value less than or equal to 15000

le

Output 4:

Prints records whose city name property contains “A”

like

 Output 5:

Prints records whose money property value is between 15000 and 22000

between

 

 

One thought on “Criteria Queries Implementation – Hibernate

Leave a Reply

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