Java Reference
In-Depth Information
The First Example with HQL
The simplest HQL query returns all objects for a given class in the database. In a syntax similar
to that of SQL, we use the HQL clause from . As noted, when retrieving objects with HQL, you
do not have to use the leading select clause for this query—instead, you can use the following
simple shortcut query to select all objects from the Product table:
from Product
n Note Like all SQL syntax, you can write from in lowercase or uppercase (or mixed case). However, any
Java classes or properties that you reference in an HQL query have to be specified in the proper case. For
example, when you query for instances of a Java class named Product , the HQL query from Product is
the equivalent of FROM Product . However, the HQL query from product is not the same as the HQL query
from Product . Because Java class names are case-sensitive, Hibernate is case-sensitive about class
names as well.
Embedding the following HQL statement into our application is straightforward. The
org.hibernate.Session object contains a method named createQuery() :
public Query createQuery(String queryString) throws HibernateException
The createQuery() method takes a valid HQL statement, and returns an org.hibernate.
Query object. The Query class provides methods for returning the query results as a Java List ,
as an Iterator , or as a unique result. Other functionality includes named parameters, results
scrolling, JDBC fetch sizes, and JDBC timeouts. You can also add a comment to the SQL that
Hibernate creates, which is useful for tracing which HQL statements correspond to which
SQL statements.
In order to fully illustrate our examples, we must first introduce the sample application
that we are using in this chapter and the next (which discusses criteria). The sample applica-
tion has three classes: Supplier , Product , and Software . The Supplier class, shown in
Listing 9-1, has a name property and a List collection of Product objects.
Listing 9-1. The Supplier Class
package com.hibernatebook.queries;
import java.util.ArrayList;
import java.util.List;
public class Supplier
{
private int id;
private String name;
private List products = new ArrayList();
Search WWH ::




Custom Search