Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare time part of datetime field in Hibernate

Tags:

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?

like image 645
Linor Avatar asked Sep 19 '08 12:09

Linor


2 Answers

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

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

like image 104
Sietse Avatar answered Sep 28 '22 18:09

Sietse


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()
  )
);
like image 43
Adam Hawkes Avatar answered Sep 28 '22 20:09

Adam Hawkes