views:

2624

answers:

2

I've got an application that uses a hibernate(annotations)/mysql combination for ORM. In that application, I got an entity with a Date field. I'm looking for a way to select on that date within a time range (so hh:mm:ss without the date part).

In MySQL there's a function TIME(expression) that can extract the time part and use that in the where clause, but that does not seem to be available in Hibernate without switching to native queries. Is there an option in hibernate to do this, or should I loop through the results in java and do the comparison there? Would this be much slower as the MySQL solution, since that would not use indexes anyway?

+4  A: 

The following functions are available in HQL, maybe you could use them:

second(...), minute(...), hour(...), day(...), month(...), year(...)

Sietse
+1  A: 

Add the expression as a SQL restriction rather than having a full native query. I don't know MySQL specifically, but imagine something like this:

Criteria criteria = session.createCriteria(MyTable.class);
criteria.add( 
  Expression.sql(
    "TIME( {alias}.my_date, 'hh:mm:ss') >= :1", 
    dateRangeMin, 
    new StringType()
  )
);
Adam Hawkes
The documentation states teh Expression is 'semi deprecated' and to use Restrictions.sqlRestriction().
Arthur Thomas
Thanks for the heads-up! We're still moving from Hibernate 2 to Hibernate 3 in our organization. I'll be sure to check that out.
Adam Hawkes