Java Reference
In-Depth Information
The distinct keyword only counts the unique values in the row set—for instance, if there
are 100 products, but 10 have the same price as another product in the results, then a select
count(distinct product.price) from Product product query would return 90 . In our data-
base, the following query will return 2 , one for each supplier:
select count(distinct product.supplier.name) from Product product
If we removed the distinct keyword, it would return 5 , one for each product.
All of these queries return an Integer object in the list. You could use the uniqueResult()
method here to obtain the result.
The aggregate functions available through HQL include the following:
avg( property name ) : The average of a property's value
count( property name or *) : The number of times a property occurs in the results
max( property name ) : The maximum value of the property values
min( property name ) : The minimum value of the property values
sum( property name ) : The sum total of the property values
If you have more than one aggregate method, the result set List will contain an Object
array with each of the aggregates you requested. Adding another aggregate to the select
clause is straightforward:
select min(product.price), max(product.price) from Product prodsuct
You can also combine these with other projection properties in the result set.
Bulk Updates and Deletes with HQL
Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than
they did in Hibernate 2. The Query interface now contains a method called executeUpdate() for
executing HQL UPDATE or DELETE statements. The executeUpdate() method returns an int that
contains the number of rows affected by the update or delete, as follows:
public int executeUpdate() throws HibernateException
HQL updates look like you would expect them to, being based on SQL UPDATE statements.
Do not include an alias with the update; instead, put the set keyword right after the class name,
as follows:
String hql = "update Supplier set name = :newName å
where name = :name";
Query query = session.createQuery(hql);
query.setString("name","SuperCorp");
query.setString("newName","MegaCorp");
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
Search WWH ::




Custom Search