使用Hibernate Criteria和Oracle,有什么更好的方法与时间一起工作?

我想按时间选择实体。 我的Oracle DBMS的字段类型为DATE,其中包含日期和时间。 这是我的代码。 如何按时间标准选择数据?

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

我找到了答案。 只需要使用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 })); 

Hibernate HQL具有可在此特定情况下使用的hourminutesecond函数,因此您可以在HQL而不是SQL中执行此操作。 因此,您需要一个HQL查询而不是Criteria对象。 HQL看起来像

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

您可以在其中适当地设置:minSeconds:maxSeconds参数。 注意以下错误:maxDate也是如此。

有关HQL的更多信息,请访问http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

您必须使用SQL限制来执行此操作,或者,您最好必须创建自己的Criterion实现,它将发出适当的SQL限制。

使用org.hibernate.criterion.IlikeExpression类作为例子:当它不使用PostgreSQL方言时,它会生成lower(columnName) like ?的SQL表达式lower(columnName) like ? ,其中表达式的参数是value.toString().toLowerCase()

您的标准应该生成类似to_date(to_char(columnName, 'HH24:MI:SS'), 'HH24:MI:SS') < ?) ,其中表达式的参数是您的最大时间。 (当然,在最短时间内做一个类似的标准)