Movatterモバイル変換


[0]ホーム

URL:


ObjectDBObjectDB
ObjectDB Manual

JPA Query Structure (JPQL / Criteria)

The syntax of the Java Persistence Query Language (JPQL) is very similar to the syntax of SQL. Having an SQL-like syntax in JPA queries is an important advantage because SQL is a very powerful query language and many developers are already familiar with it.

The main difference between SQL and JPQL is that SQL works with relational database tables, records and fields, whereas JPQL works with Java classes and objects. For example, a JPQL query can retrieve and return entity objects rather than just field values from database tables, as with SQL. That makes JPQL more object oriented friendly and easier to use in Java.

JPQL Query Structure

As with SQL, a JPQL SELECT query also consists of up to 6 clauses in the following format:

SELECT ...FROM ...[WHERE ...][GROUPBY ... [HAVING ...]][ORDERBY ...]

The first two clauses,SELECT andFROM are required in every retrieval query (update and delete queries have a slightly different form). The other JPQL clauses,WHERE,GROUP BY,HAVING andORDER BY are optional.

The structure of JPQLDELETE andUPDATE queries is simpler:

DELETEFROM ... [WHERE ...]UPDATE ...SET ... [WHERE ...]

Besides a few exceptions, JPQL is case insensitive. JPQL keywords, for example, can appear in queries either in upper case (e.g. SELECT) or in lower case (e.g. select). The few exceptions in which JPQL is case sensitive include mainly Java source elements such as names of entity classes and persistent fields, which are case sensitive. In addition, string literals are also case sensitive (e.g. "ORM" and "orm" are different values).

A Minimal JPQL Query

The following query retrieves all theCountry objects in the database:

SELECTcFROMCountryASc

BecauseSELECT andFROM are mandatory, this demonstrates a minimal JPQL query.

TheFROM clause declares one or more query variables (also known as identification variables). Query variables are similar to loop variables in programming languages. Each query variable represents iteration over objects in the database. A query variable that is bound to an entity class is referred to as a range variable. Range variables define iteration over all the database objects of a binding entity class and its descendant classes. In the query above,c is a range variable that is bound to theCountry entity class and defines iteration over all theCountry objects in the database.

TheSELECT clause defines the query results. The query above simply returns all theCountry objects from the iteration of the c range variable, which in this case is actually all theCountry objects in the database.

Organization of this Section

This section contains the following pages:

JPQL SELECTJPQL FROMJPQL WHEREJPQL GROUP BYJPQL ORDER BYDELETE QueriesUPDATE Queries

Detailed explanations on how to set criteria query clauses are provided as follows:

< Setting & Tuning^ JPA QueriesJPQL SELECT >

[8]ページ先頭

©2009-2025 Movatter.jp