What is better way to work with time, using Hibern

2019-05-17 00:39发布

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
    */
}

3条回答
欢心
2楼-- · 2019-05-17 01:26

I find answer. Just need use sqlRestriction.

criteria.add(
    Restrictions.sqlRestriction(
        " NUMTODSINTERVAL(EVENT_DATE - TRUNC(EVENT_DATE), 'DAY') BETWEEN  NUMTODSINTERVAL (?,'SECOND') AND NUMTODSINTERVAL (?,'SECOND')",
        new Object[] { secondsForBegin, secondsForEnd },
        new Type[]   { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER }));
查看更多
对你真心纯属浪费
3楼-- · 2019-05-17 01:30

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 expression lower(columnName) like ?, where the argument of the expression is value.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)

查看更多
戒情不戒烟
4楼-- · 2019-05-17 01:35

Hibernate HQL has hour, minute and second 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 like

from  tableName
where eventDate between :minDate and :maxDate
  and 3600 * hour( eventDate ) + 60 * minute( eventDate ) + second( eventDate )
      between :minSeconds and :maxSeconds

where 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

查看更多
登录 后发表回答