views:

86

answers:

1

I have two tables, Band and Votes. Band has a name and an id, and Votes has a total_votes column and a foreign key called band_id pointing to band.id.

I have lots of votes, saved at various dates. What I want to do is find the maximum value of the total_votes column for each band. The following SQL query works:

select b.name,max(v.total_votes) as total from band b, votes v 
    where b.id=v.band_id
    group by b.name order by total desc;

The system I'm working with, though, uses Hibernate. I'd like to re-write that SQL query as either HQL or a Hibernate criteria query.

Is this easy and I'm just missing it? Thanks for any help.

+1  A: 

In HQL, could you give this a try:

select band.name, max(vote.totalVotes)
from Band band
     join band.votes vote
group by band.name
order by max(vote.totalVotes) desc

This assumes there is a one-to-many association between Band and Votes (actually, providing the object model is very helpful when working with HQL and/or the Criteria API since you are querying the object model).

Just in case, here is the relevant section of the documentation:

14.12. The group by clause

A query that returns aggregate values can be grouped by any property of a returned class or components:

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color

select foo.id, avg(name), max(name)
from Foo foo join foo.names name
group by foo.id

A having clause is also allowed.

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
having cat.color in (eg.Color.TABBY, eg.Color.BLACK)

SQL functions and aggregate functions are allowed in the having and order by clauses if they are supported by the underlying database (i.e., not in MySQL).

select cat
from Cat cat
    join cat.kittens kitten
group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc

Neither the group by clause nor the order by clause can contain arithmetic expressions. Hibernate also does not currently expand a grouped entity, so you cannot write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.

Pascal Thivent