spring-boot - 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] 的转换器"
解决方案
有 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)
推荐阅读
- sql - SQL 时间戳查询:检查一个时间戳是否早于另一个
- r - 使用 rvest 和 for 循环进行高效抓取
- python - Openpyxl 模块异常
- amazon-web-services - 有什么方法可以在 Amazon redshift 中创建表(从 RDS 转移或通过 cralwer 创建)
- postgresql - 在 AWS RDS Postgres 服务器中连接不同数据库中的表
- typescript - Autodesk Forge:测量和切片不起作用 - 不是 THREE.Object3D 的实例
- reactjs - Razzle、IE11 和 HappiJS 捆绑
- java - JHipster:使用附加信息注册用户[帮助]
- outsystems - 我的导航链接未连接 OutSystems
- python - 如何配置 vscode 的 python 调试器以使用项目的终端而不是全局?