Hibernate Criteria Example Tutorial

Welcome to the Hibernate Criteria Example Tutorial. Today we will look into Criteria in Hibernate.

Hibernate Criteria

Most of the times, we use HQL for querying the database and getting the results. HQL is not preferred way for updating or deleting values because then we need to take care of any associations between tables.

Hibernate Criteria API provides object oriented approach for querying the database and getting results. We can’t use Criteria in Hibernate to run update or delete queries or any DDL statements. Hibernate Criteria query is only used to fetch the results from the database using object oriented approach.

For my Hibernate criteria example, I will use the same setup as in my HQL Example and show you how to use Criteria in Hibernate for querying databases.

Some of the common usage of Hibernate Criteria API are;

  1. Hibernate Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
  2. Hibernate Criteria API can be used with ProjectionList to fetch selected columns only.
  3. Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection()
  4. Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
  5. Hibernate Criteria API provides addOrder() method that we can use for ordering the results.

Below class shows different usages of Hibernate Criteria API, most of these are replacements of examples in HQL tutorial.

When we execute above Hibernate Criteria example program, we get following output.

Since I am using HQL example project, you would need to import that and then add this class for it to be working.

Notice the hibernate queries executed in the output, this way you can refine your queries and get the results you are looking for. That’s all for a quick roundup on Criteria in Hibernate.

By admin

Leave a Reply

%d bloggers like this: