Java Reference
In-Depth Information
The simplest example of named parameters uses regular SQL types for the parameters:
String hql = "from Product where price > :price";
Query query = session.createQuery(hql);
query.setDouble("price",25.0);
List results = query.list();
Normally, you do not know the values that are to be substituted for the named parameters—
and if you did, you would probably encode them directly into the query string. When the value to
be provided will be known only at run time, you can use some of HQL's object-oriented features
to provide objects as values for named parameters. The Query interface has a setEntity() method
that takes the name of a parameter and an object. Using this functionality, we could retrieve all
the products that have a supplier whose object we already have:
String supplierHQL = "from Supplier where name='MegaInc'";
Query supplierQuery = session.createQuery(supplierHQL);
Supplier supplier = (Supplier) supplierQuery.list().get(0);
String hql = "from Product as product where product.supplier=:supplier";
Query query = session.createQuery(hql);
query.setEntity("supplier",supplier);
List results = query.list();
You can also use regular JDBC query parameters in your HQL queries. We do not particu-
larly see any reason why you would want to, but they do work.
Paging Through the Result Set
Pagination through the result set of a database query is a very common application pattern.
Typically, you would use pagination for a web application that returned a large set of data
for a query. The web application would page through the database query result set to build
the appropriate page for the user. The application would be very slow if the web application
loaded all of the data into memory for each user. Instead, you can page through the result
set and retrieve the results you are going to display one chunk at a time.
There are two methods on the Query interface for paging: setFirstResult() and
setMaxResults() , just as with the Criteria interface. The setFirstResult() method takes
an integer that represents the first row in your result set, starting with row 0. You can tell
Hibernate to only retrieve a fixed number of objects with the setMaxResults() method.
Your HQL is unchanged—you only need to modify the Java code that executes the query.
Excuse our tiny dataset for this trivial example of pagination:
Query query = session.createQuery("from Product");
query.setFirstResult(1);
query.setMaxResults(2);
List results = query.list();
displayProductsList(results);
You can change the numbers around and play with the pagination. If you turn on SQL
logging, you can see which SQL commands Hibernate uses for pagination. For the open
source HSQLDB database, Hibernate uses top and limit .
Search WWH ::




Custom Search