Hibernate Criteria Example

By | | Updated : 2021-03-10 | Viewed : 312 times

Hibernate Criteria Example

Hibernate Criteria Api

Hibernate Criteria Interface provides a querying mechanism for the data from the database as hibernate entities. This is an alternative for JPQL and HQL. Here it is very useful for writing type-safe queries like JPQL/HQL.

Criteria And Criterion Difference

Criteria interface is the main interface for executing queries where Criterion is used for preparing the query. Please find the below given example.

Criteria vs Criterion
Criteria criteriaObject = session.createCriteria(entity.class);
Criterion criterionObject  = Restrictions.like("playerType","Bats%", MatchMode.ANYWHERE);
criteriaObject.add(criterionObject  );

In the first line, we did create the Criteria object from Session. In a query, we used to pass any number of query operators like, and or etc. So to prepare the same query operators in Hibernate it is required to add Criterion. In the next line of code if you notice the same thing is implemented and then finally added it to criteriaObject.

Criteria Api Examples

To fetch the entity list using criteria we can use the below-given code

Fetch Entity list using Criteria

Fetch List Using Criteria
Criteria crit = session.createCriteria(Cricketer.class);
List<Cricketer> results = crit.list();

Criterion in Hibernate

CriterionObject preparation will give the final query for execution to fetch the result. So Criterion objects can be formed with Restriction and Projection objects in hibernate. Here we will see here the first Restriction class example.

Restrictions Example1
criteria1.add(Restrictions.eq("playerType","Bowler"));

The above-given Criterion will be working as like operator in SQL.

Restrictions Example2
criteria2.add(Restrictions.ne("salaryIncome",450000l));

Here query will be prepared as with sql operator > for fetching the result from SQL.

Restrictions Example3
criteria4.add(Restrictions.isNull("jerseyNo"));
criteria5.add(Restrictions.isNotNull("jerseyNo"));

Here these two code snippets work as SQL operators = and !=

Restrictions Example4
criteria6.add(Restrictions.gt("salaryIncome", 450000l));
criteria7.add(Restrictions.lt("salaryIncome", 500000l));

Here in example4, these two code snippets work as SQL parameters > and <

To find more examples for Restrictions you can refer to the code repository in Github.

To create Criteria object for the SQL aggregations we should go for the Projection class. Please see the example provided below for Projection.

Projection Example
ProjectionList projList = Projections.projectionList();
projList.add(Projections.max("age"));
projList.add(Projections.min("age"));
projList.add(Projections.avg("age"));
projList.add(Projections.countDistinct("playerType"));
criteria18.setProjection(projList);

To find more examples please have a look at Github repository Hibernate-Criteria-Examples-App

Leave A Reply