2011-04-26 78 views
21

在oracle中我有格式的日期Hibernate的標準日期

17月2011年19:20:23.707000000

我想檢索所有訂單17-04-2011。

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); 
String myDate = "17-04-2011"; 
Date date = formatter.parse(myDate); 
    Criteria criteria = 
       session.createCriteria(Order.class); 
Criterion restrictDate = Restrictions.like("orderDate",date); 

,但它帶給我空的結果:

回答

43

爲何使用Restrictions.like(...)?您可以使用Restrictions.eq(...)

請注意,您還可以使用.le,.lt,.ge,.gt作爲比較運算符的日期對象。 LIKE運算符不適合這種情況,因爲LIKE在您想根據列的部分內容匹配結果時非常有用。 請參閱http://www.sql-tutorial.net/SQL-LIKE.asp以供參考。

例如,如果你有一些人的全名的名稱欄,你可以做where name like 'robert %',這樣你將返回名稱以'robert '所有條目(%可以代替任何字符)。

就你而言,你知道你試圖匹配的日期的全部內容,所以你不應該使用LIKE,而是平等。我猜Hibernate在這種情況下不會給你任何例外,但無論如何,你可能會遇到與Restrictions.eq(...)相同的問題。

你的代碼有

你的約會對象:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); 
String myDate = "17-04-2011"; 
Date date = formatter.parse(myDate); 

此Date對象是等於在17-04-2011在0H,0分0秒和0納秒。

這意味着您在數據庫中的條目必須有,該日期恰好爲。我的意思是,如果你的數據庫條目有一個日期「2011年4月17日19:20:23.707000000」,那麼它將不會被檢索,因爲你只是要求這個日期:「2011年4月17日00:00: 00.0000000000" 。

如果你想從某一天檢索數據庫的所有條目,你將不得不使用下面的代碼:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); 
    String myDate = "17-04-2011"; 
    // Create date 17-04-2011 - 00h00 
    Date minDate = formatter.parse(myDate); 
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class 
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1)); 
    Conjunction and = Restrictions.conjunction(); 
    // The order date must be >= 17-04-2011 - 00h00 
    and.add(Restrictions.ge("orderDate", minDate)); 
    // And the order date must be < 18-04-2011 - 00h00 
    and.add(Restrictions.lt("orderDate", maxDate)); 
+2

需要注意的是要明白,當你分析一個日期可能考慮要在其中解析時區是很重要很重要/格式Java日期 – 2014-09-12 17:01:52

5

通過使用這種方式,你可以得到的選定記錄列表。

GregorianCalendar gregorianCalendar = new GregorianCalendar(); 
Criteria cri = session.createCriteria(ProjectActivities.class); 
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime())); 
List list = cri.list(); 

所有記錄將被生成到列表,它是大於或等於08 - 辛2012' 或者通過用戶的認可日期的日期在(gregorianCalendar.getTime())限制的第二參數的標準,以獲得記錄。

1

如果列是一個時間戳,你可以做到以下幾點:

 if(fromDate!=null){ 
      criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')")); 
     } 
     if(toDate!=null){    
      criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')")); 
     } 

     resultDB = criteria.list();