views:

23

answers:

2

I have a table with the following structure:

ReportId
Version
Title
.....

I want to use HQL to fetch the newest version of the report by id. Would the following query work?

from Report where reportId = :reportId and version = (select max(version) from Report where reportId = :reportId)

Is it possible to retrieve the row with the maximum version without using a sub-select? Is the above sub-select even legal in hibernate HQL?

A: 

You can order by version and use setMaxResults on the query (set it to 1). As for the other question, subselects like this are legal in hql.

shipmaster
A: 

Try this query:

    from Report where reportId = :reportId order by version desc 

with setMaxResults=1

uthark
This covers 99% of the use cases, but what if I want to retrieve a list of titles for ALL of the reports? For example, a drop-down menu with the titles of ALL reports which can be produced by the system....
David
SELECT reportId, title, max(version) FROM report GROUP BY reportId. But you have to use projections in this case.
uthark