Java Reference
In-Depth Information
11.2. Criteria queries
Although JPQL is extremely powerful, it still depends on strings that are embedded within
Java code and are evaluated only at runtime. This means that despite an application compil-
ing and deploying successfully, it still may contain syntax errors. The only way to be sure
that the queries are syntactically valid is to execute each and every query via either unit
tests or integration tests. Ignoring regression testing, syntax errors are extremely expensive
during development and are especially problematic if an application is large and takes a
significant amount of time to compile, package, deploy, and then access the functionality
that executes a problematic query. Starting with Java EE 6, the criteria queries were intro-
duced to provide a type-safe mechanism for creating queries.
A type-safe API means that you'll build queries using real Java objects to represent the
SQL statement. This is completely different than the traditional non-type-safe way, which
is to build the SQL statement as a string and hope it has no syntactical errors. Using the
type-safe API, it can be built entirely in code with no hardcoded strings. The queries are
guaranteed to be syntactically correct, although they still may contain logical errors. Logic-
al errors refer to human error, such as forgetting to provide a predicate expression on the
DELETE because you were distracted by a phone call. The trade-off to this approach is that
the code will be much more verbose and unwieldy for large complex queries. A single-line
JPQL or SQL statement will span multiple lines when coded using the criteria API. Devel-
oping a domain-specific language (DSL) can be used to address this issue but is outside the
scope of this topic and chapter.
At this point, you might be wondering about mechanics and specifically how you can get
static typing on properties. Obviously you need a data model to provide this support. This
is where the meta-model comes in. The meta-model is a static representation of the data
model. The compiler generates it for you using a JPA annotation processor. The meta-mod-
el is used in conjunction with the CriteriaBuilder to construct and execute a query.
To put this discussion into context, let's examine a simple query to locate an item by name,
as shown in the following listing.
Search WWH ::




Custom Search