I want to select entity by Time. I have Oracle DBMS with field type DATE which contain date and time. This is my code. How to select data by Time criteria?
Calendar timeCal = new GregorianCalendar(0,0,0,0,0,0);
Date timeMin = timeCal.getTime();
timeCal.add(Calendar.HOUR_OF_DAY, 1);
Date timeMax = timeCal.getTime();
if (minDate != null && maxDate != null)
criteria.add(Restrictions.between("eventDate", minDate, maxDate));
if (onDate != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(onDate);
calendar.add(Calendar.DAY_OF_MONTH, 1);
criteria.add(Restrictions.between("eventDate", onDate, calendar.getTime()));
}
if(minTime!=null&&maxTime!=null){
/*
How to add Restriction on eventDate field, for time only?
if minTime is 3:00 and maxTime is 16:00, must to return
all rows having the time part of their eventDate between
3:00 and 16:00, regardless of the date part
*/
}
I find answer. Just need use sqlRestriction.
You'll have to use a SQL restriction to do that, or, preferrably, you'll have to create your own Criterion implementation, which will issue the appropriate SQL restriction.
Use the
org.hibernate.criterion.IlikeExpression
class as an exemple: when it's not using the PostgreSQL dialect, it generates the SQL expressionlower(columnName) like ?
, where the argument of the expression isvalue.toString().toLowerCase()
.Your criterion should generate something like
to_date(to_char(columnName, 'HH24:MI:SS'), 'HH24:MI:SS') < ?)
where the argument of your expression is your max time. (And of course, do a similar criterion for the min time)Hibernate HQL has
hour
,minute
andsecond
functions that you can use in this particular case, so you can do this in HQL, rather than SQL. So you'll need an HQL query instead of a Criteria object. The HQL will look something likewhere you'll set the
:minSeconds
and:maxSeconds
parameters appropriately. Watch out for out-by-one errors with:maxDate
too.More information on HQL can be found at http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html