Understanding EclipseLink, 2.5
  Go To Table Of Contents
 Search
 PDF

About JPQL Queries

The Java Persistence Query Language (JPQL) is the query language defined by JPA. JPQL is similar to SQL, but operates on objects, attributes and relationships instead of tables and columns. JPQL can be used for reading (SELECT), as well as bulk updates (UPDATE) and deletes (DELETE). JPQL can be used in a NamedQuery (through annotations or XML) or in dynamic queries using the EntityManager createQuery() API.

The disadvantage of JPQL is that dynamic queries require performing string concatenations to build queries dynamically from web forms or dynamic content. JPQL is also not checked until runtime, making typographical errors more common. These disadvantages are reduced by using the query criteria API, described in the next section.

For more information, see Chapter 4 "Query Language" in the JPA Specification.

http://jcp.org/en/jsr/detail?id=317

Select Queries

Select queries can be used to read objects from the database. Select queries can return a single object or data element, a list of objects or data elements, or an object array of multiple objects and data.

SELECT Clause

The SELECT clause can contain object expressions, attribute expressions, functions, sub-selects, constructors and aggregation functions.

Aggregation functions

Aggregation functions can include summary information on a set of objects. These include MIN, MAX, AVG, SUM, COUNT. These functions can be used to return a single result, or can be used with a GROUP BY to return multiple results.

Constructors

The NEW operator can be used with the fully-qualified class name to return data objects from a JPQL query. These will not be managed objects, and the class must define a constructor that matches the arguments of the constructor and their types. Constructor queries can be used to select partial data or reporting data on objects, and get back a class instance instead of an object array.

FROM Clause

The FROM clause defines what is being queried. A typical FROM clause will contain the entity name being queried and assign it an alias.

JPQL allows for multiple root level objects to be queried. Caution should be used when doing this, as it can result in Cartesian products of the two tables. The WHERE or ON clause should ensure the two objects are joined in some way.

The entity name used in JPQL comes from the name attribute of the @Entity annotation or XML. It defaults to the simple entity class name. EclipseLink also allows for the fully-qualified class name of the entity to be used.

JOIN

A JOIN clause can also be used in the FROM clause. The JOIN clause allows any of the object's relationships to be joined into the query so they can be used in the WHERE clause. JOIN does not mean the relationships will be fetched, unless the FETCH option is included.

JOIN can be used with OneToOne, ManyToOne, OneToMany, ManyToMany and ElementColleciton mappings. When used with a collection relationship you can join the same relationship multiple times to query multiple independent values.

JOIN FETCH

The FETCH option can be used on a JOIN to fetch the related objects in a single query. This avoids additional queries for each of the object's relationships, and ensures that the relationships have been fetched if they were LAZY. EclipseLink also supports batch fetching through query hints.

JOIN FETCH normally allows an alias. The alias should be used with caution, as it can affect how the resulting objects are built. Objects should normally always have the same data, no matter how they were queried, this is important for caching and consistency. This is only an issue if the alias is used in the WHERE clause on a collection relationship to filter the related objects that will be fetched. This should not be done, but is sometimes desirable, in which case the query should ensure it has been set to BYPASS the cache.

LEFT JOIN

By default all joins in JPQL are INNER joins. This means that results that do not have the relationship will be filtered from the query results. To avoid this, a join can be defined as an OUTER join using the LEFT options.

ON

The JOIN condition used for a join comes from the mapping's join columns. This means that the JPQL user is normally free from having to know how every relationship is joined. In some cases it is desirable to append additional conditions to the join condition, normally in the case of outer joins. This can be done through the ON clause. EclipseLink also supports usage of the ON clause between two root level objects.

For INNER joins, EclipseLink will normally append the join condition to the WHERE clause, but this can be configured in the DatabasePlatform.

Sub-selects in FROM clause

Sub-selects are supported in the FROM clause. This requires that the database supports this functionality.

ORDER BY clause

ORDER BY allows the ordering of the results to be specified. Multiple values can be ordered, either ascending (ASC) or descending (DESC). EclipseLink allows functions, sub-selects and other operations in the ORDER BY clause. EclipseLink allows objects expressions to be used in the ORDER BY. In the case of entity objects, they are ordered by their Id, in case of embeddable objects, they are ordered by all of their fields. EclipseLink also allows for NULL ordering to be specified (either FIRST or LAST).

GROUP BY Clause

GROUP BY allows for summary information to be computed on a set of objects. GROUP BY is normally used in conjunction with aggregation functions. EclipseLink supports using objects, functions and sub-selects in the GROUP BY clause.

HAVING Clause

The HAVING clause allows for the results of a GROUP BY to be filtered. EclipseLink supports using comparisons, objects, functions and sub-selects in the HAVING clause.

UNION

EclipseLink supports UNION, INTERSECT and EXCEPT operations. UNION allows the results of two queries with equivalent result structures to be combined into a single query. The unique results from both queries will be returned. If the ALL option is used, then results found in both queries will be duplicated.

INTERSECT returns only the results that are found in both queries. EXCEPT removes the results from the second query from the results from the first query.

The JPA spec does not support union operations.

WHERE Clause

The WHERE clause is normally the main part of the query as it defines the conditions that filter what is returned. The WHERE clause can use any comparison operation, logical operation, functions, attributes, objects, and sub-selects. The comparison operations include =, <, >, <=, >=, <>, LIKE, BETWEEN, IS NULL, and IN. NOT can also be used with any comparison operation (NOT LIKE, NOT BETWEEN, IS NOT NULL, NOT IN). The logical operations include AND, OR, and NOT.

EclipseLink also supports the REGEXP operation to perform regular expression comparisons (requires database to support regular expressions). EclipseLink allows for functions and sub-selects to be used with any operation.

The IN operation allows for a list of values or parameters, a single list parameter, or a sub-select.

A sub-select can be used with any operation provided it returns a single value, or if the ALL or ANY options are used. ALL indicates the operation must be true for all elements returned by the sub-select, ANY indicates the operation must be true for any of the elements returned by the sub-select.

EclipseLink allows the =, <>, IS NULL, IS NOT NULL, IN and NOT IN operations on objects. If IN is used on an object and the object has a composite Id, this requires the database to support nested IN lists.

Update Queries

You can perform bulk update of entities with the UPDATE statement. This statement operates on a single entity type and sets one or more single-valued properties of the entity subject to the condition in the WHERE clause. Update queries provide an equivalent to the SQL UPDATE statement, but with JPQL conditional expressions.

Update queries do not allow joins, but do support sub-selects. OneToOne and ManyToOne relationships can be traversed in the WHERE clause. Collection relationships can still be queried through using an EXISTS in the WHERE clause with a sub-select. Update queries can only update attributes of the object or its embeddables, its relationships cannot be updated. Complex update queries are dependent on the database's update support, and may make use of temp tables on some databases.

Update queries should only be used for bulk updates, regular updates to objects should be made by using the object's set methods within a transaction and committing the changes.

Update queries return the number of modified rows on the database (row count).

The persistence context is not updated to reflect results of update operations. If you use a transaction-scoped persistence context, you should either execute the bulk operation in a transaction all by itself, or be the first operation in the transaction. That is because any entity actively managed by the persistence context will remain unaware of the actual changes occurring at the database level.

The objects in the shared cache that match the update query will be invalidated to ensure subsequent persistence contexts see the updated data.

Delete Queries

You can perform bulk removal of entities with the DELETE statement. Delete queries provide an equivalent to the SQL DELETE statement, but with JPQL conditional expressions.

Delete queries do not allow joins, but do support sub-selects. OneToOne and ManyToOne relationships can be traversed in the WHERE clause. Collection relationships can still be queried through using an EXISTS in the WHERE clause with a sub-select. Complex delete queries are dependent on the database's delete support, and may make use of temp tables on some databases.

Delete queries should only be used for bulk deletes, regular deletes to objects should be performed through calling the EntityManager remove() API.

Delete queries return the number of deleted rows on the database (row count).


NoteNote:

Delete queries are polymorphic: any entity subclass instances that meet the criteria of the delete query will be deleted. However, delete queries do not honor cascade rules: no entities other than the type referenced in the query and its subclasses will be removed, even if the entity has relationships to other entities with cascade removes enabled. Delete queries will delete the rows from join and collection tables.


The persistence context is not updated to reflect results of delete operations. If you use a transaction-scoped persistence context, you should either execute the bulk operation in a transaction all by itself, or be the first operation in the transaction. That is because any entity actively managed by the persistence context will remain unaware of the actual changes occurring at the database level.

The objects in the shared cache that match the delete query will be invalidated to ensure subsequent persistence contexts do not see the removed objects.

Parameters

JPA defines named parameters, and positional parameters. Named parameters can be specified in JPQL using the syntax :<name>. Positional parameters can be specified in JPQL using the syntax ? or ?<position>. Positional parameters start at position 1 not 0.

Literals

Literal values can be in-lined in JPQL for standard Java types. In general it is normally better to use parameters instead of in-lining values. In-lined arguments will prevent the JPQL from benefiting from the JPQL parser cache, and can potentially make the application vulnerable to JPQL injections attacks.

Each Java type defines its own in-lining syntax:

  • String - '<string>'

    To define a ' (quote) character in a string, the quote is double quoted, i.e. 'Baie-D''Urfé'.

  • Integer - +|-<digits>

  • Long - +|-<digits>L

  • Float - +|-<digits>.<decimal><exponent>F

  • Double - +|-<digits>.<decimal><exponent>D

  • Boolean - TRUE | FALSE

  • Date - {d'yyyy-mm-dd'}

  • Time - {t'hh:mm:ss'}

  • Timestamp - {ts'yyyy-mm-dd hh:mm:ss.nnnnnnnnn'} -

  • Enum - package.class.enum

  • null - NULL

Functions

JPQL supports several database functions. These functions are database independent in name and syntax, but require database support. If the database supports an equivalent function, then the standard JPQL function is supported. If the database does not provide any way to perform the function, then it is not supported. For mathematical functions (+, -, /, *) BEDMAS rules apply.

In JPQL, support functions can be used in the SELECT, WHERE, ORDER BY, GROUP BY and HAVING clauses, as well as inside other functions, with comparison operators, and in constructors.

EclipseLink provides support for several functions beyond the JPA spec. EclipseLink also supports calling specific database functions through FUNCTION, FUNC, and OPERATOR.

EclipseLink Special Operators

EclipseLink defines several special JPQL operators that allow performing database operations that are not possible in basic JPQL. These include:

  • FUNCTION

  • OPERATOR

  • SQL

  • COLUMN

For descriptions of these operators, see "Special Operators" in Java Persistence API (JPA) Extensions Reference for EclipseLink.

EclipseLink Extensions

EclipseLink provides many extensions to the standard JPA JPQL. These extensions provide access to additional database features many of which are part of the SQL standard, provide access to native database features and functions, and provide access to EclipseLink specific features.

EclipseLink's JPQL extensions include:

  • Less restrictions than JPQL, allows sub-selects and functions within operations such as LIKE, IN, ORDER BY, constructors, functions etc.

  • Allow != in place of <>

  • FUNCTION operation to call database specific functions

  • TREAT operation to downcast related entities with inheritance

  • OPERATOR operation to call EclipseLink database independent functions

  • SQL operation to mix SQL with JPQL

  • CAST and EXTRACT functions

  • REGEXP function for regular expression querying

  • Usage of sub-selects in the SELECT and FROM clause

  • ON clause support for defining JOIN and LEFT JOIN conditions

  • Joins between independent entities

  • Usage of an alias on a JOIN FETCH

  • COLUMN operation to allow querying on non mapped columns

  • TABLE operation to allow querying on non mapped tables

  • UNION, INTERSECT, EXCEPT support

  • Usage of object variables in =, <>, IN, IS NULL, and ORDER BY

For descriptions of these extensions, see "EclipseLink Query Language" in Java Persistence API (JPA) Extensions Reference for EclipseLink.