我有一种方法试图根据日期查找所有记录。我正在使用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)是 不适用于参数(字符串)。
如何使它正常工作?谢谢!
答案 0 :(得分:0)
您的getCurrentAppt
方法正在等待一个Date
参数,但是您正在传递dateFormat.format(currentDate)
并返回一个String
。
SimpleDateFormat
的{{1}}方法用于根据指定格式将format
格式化为Date
。
您不需要格式化日期以匹配数据库格式,只需将日期作为参数传递即可:
String
如果需要显示它,则可以像已经进行的操作一样对其进行格式化:
ArrayList<Serviceappt> theList = apptRepository.getCurrentAppt(currentDate);