簡體   English   中英

嘗試按日期查詢時如何使用Spring JPA進行自定義查詢?

[英]How to use Spring JPA for a custom query when trying to query by date?

我有一種方法試圖根據日期查找所有記錄。 我正在使用MySQL,數據類型為date。 在數據庫中,格式為“ 2019-02-22”。

如何使用Spring JPA信息庫以這種形式搜索日期?

我嘗試使用SimpleDateFormat格式更改格式,但是隨后出現錯誤,提示將數據類型更改為String。 我不希望它是字符串,我希望數據類型保留日期。 怎么做?

這是存儲庫:

@Query(value="SELECT alttransport, customerfull, serviceadv, waitflag, apptdate FROM service WHERE apptdate=:currentDate", nativeQuery=true)
ArrayList<Serviceappt> getCurrentAppt(@Param("currentDate") Date currentDate);

這是給我錯誤的方法:

@Override
public ArrayList<Serviceappt> getAppts(Date currentDate) {
    final SimpleDateFormat dateFormat= new SimpleDateFormat("MM/dd/yyyy");
    log.info("the date is: "+ dateFormat.format(currentDate));
    ArrayList<Serviceappt> theList = apptRepository.getCurrentAppt(dateFormat.format(currentDate));
    for(Serviceappt appt: theList){
        log.info("the customer is: "+appt.getCustomerfull());
    }
    return theList;
 }

錯誤是:

ServiceapptRepository類型的方法getCurrentAppt(Date)不適用於參數(字符串)。

我該如何工作? 謝謝!

您的getCurrentAppt方法正在等待Date參數,但是您傳遞的dateFormat.format(currentDate)返回String

SimpleDateFormatformat方法用於根據指定的格式將Date格式化為String

您無需格式化日期即可匹配數據庫格式,只需將日期作為參數傳遞即可:

ArrayList<Serviceappt> theList = apptRepository.getCurrentAppt(currentDate);

如果需要顯示它,則可以像已經那樣設置它的格式:

log.info("the date is: "+ dateFormat.format(currentDate));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM