Home » JPA Criteria API Introduction

JPA Criteria API Introduction

by Online Tutorials Library

JPA Criteria API

The Criteria API is one of the most common ways of constructing queries for entities and their persistent state. It is just an alternative method for defining JPA queries.

Criteria API defines a platform-independent criteria queries, written in Java programming language. It was introduced in JPA 2.0. The main purpose behind this is to provide a type-safe way to express a query.

Steps to create Criteria Query

To create a Criteria query, follow the below steps: –

  • Create an object of CriteriaBuilder interface by invoking getCriteriaBuilder() method on the instance of EntityManager interface.
  • Now, build an instance of CriteriaQuery interface to create a query object.
  • Call from method on CriteriaQuery object to set the query root.
  • Now, call the select method of CriteriaQuery Object to specify type of query result.
  • Create an instance of Query interface and specify the type of method used to access the database records
  • Now, control the execution of query by calling the methods of Query Interface.

Methods of Criteria API Query Clauses

Following is the list of clauses with the corresponding interface and methods.

Clause Criteria API Interface Methods
SELECT CriteriaQuery select()
FROM AbstractQuery from()
WHERE AbstractQuery where()
ORDER BY CriteriaQuery orderBy()
GROUP BY AbstractQuery groupBy()
HAVING AbstractQuery having()

Note: – The CriteriaQuery interface is the sub-interface of AbstractQuery interface.

You may also like