2014-02-24 30 views
1

下面給出的是我的Domain對象。grails或hibernate標準只能按時間組件搜索

Game { 
    Date startDate 
} 

現在我只想搜索早上開始於hh:mm AM(動態搜索)的遊戲,無論日期如何。我正在尋找像這樣的Grails標準

Game.where { 
    startDate.timePart == timeValue 
}.list() 

where timeValue =「10:30 AM」或類似的東西。

由於在GORM中不支持一些自定義限制,因此我使用Hibernate標準,所以如果有人知道如何使用Hibernate標準來做到這一點,那將會很好。

現在,這是我正在試圖在Hibernate Criteria中做什麼,它不工作(我正在使用Postgre)。

searchCriteria.add(Restrictions.sqlRestriction("to_timestamp(start_date, 'h:mm a') = ? ", timeValue, StandardBasicTypes.DATE)) 

非常感謝您的幫助。

回答

0

您可以使用HibernateCriteriaBuilder。 構建器可通過「個createCriteria()」動態靜態Grails領域類的方法進行檢索:

def c = Game.createCriteria() 
    def results = c { 
    eq("start_date",timeValue) 
    } 

助洗劑也可以實例化單獨帶有一個會話和持久Class實例:

new HibernateCriteriaBuilder(clazz, sessionFactory).list { 
    eq("start_date", timeValue) 
    } 
+0

@Fahimah - 非常感謝您的回覆。如果我嘗試使用您的實現,那麼grails標準將嘗試將「start_date」作爲日期。我想要的只是比較時間組件。從GUI開始,用戶將輸入類似於上午10:30的內容,並且無論日期如何,我都必須列出此時開始的所有比賽。 – manish

0

您可以僅使用時間獲取Date實例,並在Hibernate Criteria API中使用該實例進行查詢。

Compare date's date part only with Timestamp in Hibernate

+0

如果我只用時間創建Date實例,它將不起作用,因爲「startDate」是保存在數據庫中的時間戳,並且僅將它與時間進行比較將不會返回預期結果。 – manish