首页 > 解决方案 > Springboot / JPA-将日期传递给 REST API 中的控制器-无法将 PathVariable java.sql.Date 转换为 java.sql.Date

问题描述

我有 DB2 表,其中 SOLD_DATE 字段是 TIMESTAMP 类型(例如 2017-12-07 08:43:23)。

我希望能够将提供如下开始和结束日期 URL 参数的 URL 发送到我的控制器:

http://localhost:8080/irwapi/v1/logs/2014-10-20/2021-10-20

我的控制器看起来像:

@GetMapping(path = "/{startDate}/{endDate}")
public List<CarResponse> getCarsSoldBetween(
    @PathVariable("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, 
    @PathVariable("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
  List<CarResponse> cars = myRepository.getCarsSoldBetween(startDate, endDate);
  return cars;
}

myRepository 的@Query方法定义如下:

@Query("select c from CarEntity c where c.carType = 'SPORT' and C.soldDate between  ?1 and ?2") 
List<CarEntity> getCarsSoldBetween(Date startDate, Date endDate);

当我执行上面的方法时,上面的方法@Query会抛出错误:

“无法将 'java.lang.String' 类型的值转换为所需类型 'java.sql.Date';嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为值“2014-10-20”键入 [@org.springframework.web.bind.annotation.PathVariable @org.springframework.format.annotation.DateTimeFormat java.sql.Date];嵌套异常是 org.springframework.core。 convert.ConverterNotFoundException:找不到能够从类型 [java.util.Date] 转换为类型 [@org.springframework.web.bind.annotation.PathVariable @org.springframework.format.annotation.DateTimeFormat java.sql.Date] 的转换器"

标签: spring-bootspring-data-jpatimestampdb2

解决方案


有 2 个选项可以解决此问题。

1.在控制器级别,适用于控制器内的所有请求。

@InitBinder     
public void initBinder(WebDataBinder binder){       binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true, 10));    
}

现场级别的选项 2。

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.DATE)

推荐阅读