views:

280

answers:

2

I have a class User with one field called birthDate which is a java.sql.Date. How do I do a hql query that will retrieve all Users that are between min and max years old?

(My real scenario is slightly more complex than that but that's where I am stuck right now).

UPDATE

It must be an hql expression so I can put the age expression in a computed property.

+3  A: 

Calculate the birth dates corresponding to the min and max ages. Then use the below HQL.

Select u from User u where u.birthDate between :minDate and :maxDate

Setup the the minDate and maxDate to the values you computed before executing the query.

Chandru
+1 good idea, but I wanted an hql expression which I could then put in a computed field.
flybywire
Is there a specific reason why you want the computation to happen strictly inside the query? AFAIK HQL does not support date arithmetic. But you can use native SQL with Hibernate to perform them in the query. I'm not sure if the scenario is worth trading off DB independence by using native SQL.
Chandru
A: 

It depends on the database. Most have some way of handling date arithmetic. MySQL has a datediff function that will return a number of days so you could divide that by 365 and get pretty close. The MySQL dialect already has datediff as a registered function. For other databases you may need to use different functions and possibly register them in a custom dialect. But you may be off by a little unless you take leap years into account which is tricky in an HQL expression. Using dates is easier because you can keep the month and day constant, change the year, and then use < or > in HQL.

Brian Deterling