Java Reference
In-Depth Information
Chapter 16. Creating and Using String-Based Criteria
Queries
This chapter describes how to create weakly-typed string-based Criteria API queries.
The following topics are addressed here:
• “ Overview of String-Based Criteria API Queries ” on page 293
• “ Creating String-Based Queries ” on page 294
• “ Executing String-Based Queries on page 295
Overview of String-Based Criteria API Queries
String-based Criteria API queries (“string-based queries”) are Java programming language
queries that use strings rather than strongly-typed metamodel objects to specify entity at-
tributes when traversing a data hierarchy. String-based queries are constructed similarly to
metamodel queries, can be static or dynamic, and can express the same kind of queries and
operations as strongly-typed metamodel queries.
Strongly-typed metamodel queries are the preferred method of constructing Criteria API
queries. The main advantage of string-based queries over metamodel queries is the ability
to construct Criteria queries at development time without the need to generate static
metamodel classes or otherwise access dynamically generated metamodel classes. The
main disadvantage to string-based queries is their lack of type safety, which may lead to
runtime errors due to type mismatches that would be caught at development time when us-
ing strongly-typed metamodel queries.
For information on constructing criteria queries, see Chapter 22 , “Using the Criteria API to
Create Queries,” in The Java EE 6 Tutorial: Basic Concepts .
Creating String-Based Queries
To create a string-based query, specify the attribute names of entity classes directly as
strings, rather than the attributes of the metamodel class. For example, this query finds all
Pet entities where the value of the name attribute is Fido :
Click here to view code image
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.where(cb.equal( pet.get("name") , "Fido"));
...
Search WWH ::




Custom Search