2016-11-17 111 views
0

我有以下HQL,我想知道它如何處理比較日期列爲空。例如,如果給定的時間參數爲空,會發生什麼情況。我檢查並得到空的結果。情況總是如此嗎?有記錄嗎?休眠HQL比較時間戳爲空

select mo from MyClassMO mo 
where mo.creationDate is not null and mo.creationDate >= (:givenTime) 

什麼,如果givenTime取代,後者返回null內選擇查詢? 感謝

+0

如果givenTime爲NULL,則必須手動管理。 –

回答

0

如果你的參數是空的,你必須手動管理。

在您的應用邏輯的基礎上,您可以編寫查詢。

我想某些情況下(告訴我,如果你的是這些或另一個)。

案例1:不考慮givenTime過濾器

您可以WIRTE此查詢:

String hql = "select mo from MyClassMO mo" + 
    " where mo.creationDate is not null"; 

if (givenTime != null) { 
    hql += " and mo.creationDate >= (:givenTime)"; 
} 

案例2:如果givenTime爲null,把當前的日期

String hql = "select mo from MyClassMO mo" + 
    " where mo.creationDate is not null " + 
    " and mo.creationDate >= COALESCE(:givenTime, current_date())"; 

案例3:如果givenTime是子查詢返回NULL,把當前日期

String hql = "select mo from MyClassMO mo" + 
    " where mo.creationDate is not null " + 
    " and mo.creationDate >= " 
    " (SELECT COALESCE(:giventime, current_date()) " + 
    " FROM yourtable WHERE conditions"; 
+0

以及如果給定時間替換爲返回null的內部選擇查詢? – user1116377

0

我知道你問的HQL,但處理這樣的情況下,我更喜歡使用一些所謂的標準中休眠。它可以與SQL輕鬆混合。

JPA and Hibernate - Criteria vs. JPQL or HQL

Criteria criteria = session 
      .createCriteria(MyClassMO.class) 
       .add(Restrictions.isNotNull("creationDate")); 
if (givenTime!=null){ 
    criteria.add(Restrictions.ge("creationDate", givenTime));//ge - greater equals 
} 
List<MyClassMO> result = criteria.list(); 
+0

以及如果將givenTime替換爲返回null的內部select查詢會怎麼樣? – user1116377