2012-01-16 30 views
3

我想按时间选择实体。 我有包含日期​​和时间的字段类型为DATE的Oracle DBMS。这是我的代码。如何按时间标准选择数据?使用Hibernate Criteria和Oracle,什么是更好的工作方式?

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

您发布的代码有什么问题? – 2012-01-16 07:25:23

+0

未执行minTime!= null && maxTime!= null表达式 – Selector 2012-01-16 07:28:26

+0

我们不知道这些标准是什么,以及查询应该执行什么操作。 – 2012-01-16 07:30:16

回答

2

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

你将不得不使用一个SQL限制要做到这一点,或者,preferrably,你必须创建自己的标准执行,这会发出相应的SQL限制。

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

你的标准应该产生类似to_date(to_char(columnName, 'HH24:MI:SS'), 'HH24:MI:SS') < ?)的东西,其中表达的论点是你最大的时间。 (当然,做一个类似的标准为分钟时间)

+0

很脏的方式。 – Selector 2012-01-16 14:00:48

1

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参数。请注意0​​也有错误。

的HQL更多信息可以在http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

+0

查询对于仅用于hql和数据的部分非常重要。 – Selector 2012-01-16 13:59:54

相关问题