Java Reference
In-Depth Information
CHAPTER 10
n n n
Advanced Queries
Using Criteria
H ibernate provides three different ways to retrieve data. We have already discussed HQL and
the use of native SQL queries—now we add criteria.
The Criteria Query API lets you build nested, structured query expressions in Java, pro-
viding a compile-time syntax-checking that is not possible with a query language like HQL or
SQL. The Criteria API also includes query by example (QBE) functionality—this lets you sup-
ply example objects that contain the properties you would like to retrieve instead of having
to spell the components of the query out step by step. It also includes projection and aggre-
gation methods, including counts.
In this chapter, we explore the use of the Criteria API using the sample database estab-
lished in the previous chapter.
Using the Criteria API
The Criteria API allows you to build up a criteria query object programmatically—the
org.hibernate.Criteria interface defines the available methods for one of these objects. The
Hibernate Session interface contains several createCriteria() methods. Pass the persistent
object's class or its entity name to the createCriteria() method, and Hibernate will create a
Criteria object that returns instances of the persistence object's class when your application
executes a criteria query.
The simplest example of a criteria query is one with no optional parameters or restric-
tions—the criteria query will simply return every object that corresponds to the class.
Criteria crit = session.createCriteria(Product.class);
List results = crit.list();
When you run this example with our sample data, you will get all objects that are
instances of the Product class—note that this includes any instances of the Software class
because they are derived from Product .
Moving on from this simple example, we will add constraints to our criteria queries so
we can winnow down the result set.
213
Search WWH ::




Custom Search