Java Reference
In-Depth Information
run a projection query on the products in the database that only returned the names, instead
of loading the full object into memory, as follows:
select product.name from Product product
The result set for this query will contain a List of Java String objects. Additionally, we can
retrieve the prices and the names for each product in the database, like so:
select product.name, product.price from Product product
This result set contains a List of Object arrays—each array represents one set of proper-
ties (in this case, a name and price pair).
If you're only interested in a few properties, this approach can allow you to reduce net-
work traffic to the database server and save memory on the application's machine.
Using Restrictions with HQL
As with SQL, you use the where clause to select results that match your query's expressions.
HQL provides many different expressions that you can use to construct a query. In the HQL
language grammar, there are the following possible expressions:
Logic operators : OR , AND , NOT
Equality operators : = , <> , != , ^=
Comparison operators : < , > , <= , >= , like , not like , between , not between
Math operators : + , - , * , /
Concatenation operator : ||
Cases : Case when <logical expression> then <unary expression> else
_ <unary expression> end
Collection expressions : some , exists , all , any
In addition, you may also use the following expressions in the where clause:
HQL named parameters : :date , :quantity
JDBC query parameter : ?
Date and time SQL-92 functional operators : current_time() , current_date() ,
current_timestamp()
SQL functions (supported by the database) : length() , upper() , lower() , ltrim() ,
rtrim() , etc.
Using these restrictions, you can build a where clause in HQL that is as powerful as an SQL
query. For many queries, HQL syntax is more compact and elegant than the Criteria Query API
syntax (discussed in Chapter 10). For instance, here is an example of a criteria query that uses
logical expressions:
Search WWH ::




Custom Search