views:

49

answers:

3

Can HQL queries do this?

"get the UserEntity where the property creationTimestamp is the most recent of all UserEntities".

Essentially a query to return the "newest user" in our program where each UserEntity has a field mapped to a timestamp column in our database.

A: 

Have you looked at the HQL order-by clause?

The MYYN
+4  A: 

The HQL query to list the users from newest first is:

from UserEntities
order by creationTimestamp desc

Use setMaxResults to limit the result set to just one user.

Mark Byers
+4  A: 

Querying for the highest creationTimestamp would look like this:

from UserEntity where creationTimestamp = max(creationTimestamp)

If you want to return only a single instance and ignore other results that have the same (highest) value on that property, you can use query.uniqueResult().

See Chapter 14. HQL: The Hibernate Query Language for further reference.

codescape
+1 for pointing out select is not needed. But I am wondering, could your query in theory return more than one user in some situations?
Mark Byers
That's correct! It can return more than one but the question was to find where a property is the highest... which item do you expect when multiple have the highest value on that property?
codescape