2012-01-16 26 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

相關問題