Red Hat Training

A Red Hat training course is available for Red Hat JBoss Web Server

14.17. HQL Tips

You can count the number of query results without returning them:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
To order a result by the size of a collection, use the following query:
from User as usr
    left join usr.messages as msg
group by,
order by count(msg)
If your database supports subselects, you can place a condition upon selection size in the where clause of your query:
from User usr where size(usr.messages) >= 1
If your database does not support subselects, use the following query:
from User usr
    join usr.messages msg
group by,
having count(msg) >= 1
As this solution cannot return a User with zero messages because of the inner join, the following form is also useful:
from User as usr
    left join usr.messages as msg
group by,
having count(msg) = 0
Properties of a JavaBean can be bound to named query parameters:
Query q = s.createQuery("from foo Foo as foo where and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
Collections are pageable by using the Query interface with a filter:
Query q = s.createFilter( collection, "" ); // the trivial filter
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
Collection elements can be ordered or grouped using a query filter:
Collection orderedCollection = s.createFilter( collection, "order by this.amount" ).list();
  Collection counts = s.createFilter( collection, "select this.type, count(this) group by this.type" ).list();
You can find the size of a collection without initializing it:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue();