JPA query language

The Java™ persistence query language (JPQL) is used to define searches against persistent entities independent of the mechanism that is used to store those entities.

JPQL is therefore portable, and not constrained to any particular data store.

JPQL is an extension of the Enterprise JavaBeans query language, EJB QL, and is designed to combine the syntax and simple query semantics of SQL with the expressiveness of an object-oriented expression language.

JPQL works with JPA elements in the following way:
  • The application creates an instance of the javax.persistence.EntityManager interface.
  • The EntityManager creates an instance of the javax.persistence.Query interface, through its public methods, for example createNamedQuery.
  • The Query instance runs a query (to read or update entities).

Query instances are created using the methods that are exposed by the EntityManager interface.

Named queries

JPQL defines two types of queries: dynamic queries, which are created on the fly, and named queries.

Named queries are intended to be used in contexts where the same query is started several times. Their main benefits include the improved reusability of the code, a minor maintenance effort, and potentially better performance, because they are evaluated once.

Named queries are defined using the @NamedQuery annotation. The name attribute is used to uniquely identify the named query, while the query attribute defines the query.