hibernate QBC日期查詢

來源:互聯網
上載者:User

標籤:style   io   使用   sp   on   資料   2014   bs   cti   

    使用QBC方式查詢資料庫,如果查詢條件包含日期,則比較難以處理,尤其是在不是簡單的在某個日期之前,或在某個日期之後的情況時,不能用hibernate常用方式,要用原生sql語句執行查詢。

    1、hibernate常用方式

    方法                          說明   
    Restrictions.eq           =  
    Restrictions.allEq        利用Map來進行多個等於的限制   
    Restrictions.gt           >   
    Restrictions.ge           >=   
    Restrictions.lt            < 
    Restrictions.le            <=   
    Restrictions.between  BETWEEN  
    Restrictions.like         LIKE  
    Restrictions.in            in  
    Restrictions.and         and  
    Restrictions.or           or  

    使用以上格式進行日期的簡單比較,舉例:

    Criteria crit = session.createCriteria(TpPcdaily.class); 

    crit.add(Restrictions.eq("ppRepdate", nowdate));

    其中TpPcdaily為資料庫表對應在程式中的持久化類,ppRepdate為持久化類日期類型欄位,nowdate為日期參數,要求必須為日期類型。

    2、原生sql語句

    Restrictions.sqlRestriction     用SQL限定查詢

    使用原生sql語句可以大大擴充QBC方式,舉例:

    Criteria crit = session.createCriteria(TpPcdaily.class);

    crit.add(Restrictions.sqlRestriction("datediff(month, {alias}.PM_REPDATE, ‘"+onedate+"‘)=0"));

    其中TpPcdaily為資料庫表對應在程式中的持久化類,由於使用原生sql語句,故要使用資料庫中的欄位,PM_REPDATE為資料庫表日期類型欄位,onedate為日期參數,要求必須為String類型。{alias}表示將被替換成查詢實體的列別名,通過觀察後台運行,發現後台執行的語句為this_ where datediff(month, this_.PM_REPDATE, ‘2014-12-01‘)=0,可見在執行過程不完全是我們寫的sql語句,而是對欄位或其他一下詞語進行修飾,比如在前增加類似this_的修飾,{alias}被替換成this_。

   

hibernate QBC日期查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.