【发布时间】:2021-02-09 19:56:54
【问题描述】:
我需要将 dateTs 从 rest 控制器类方法传递到服务类中的 getCars() 方法,该方法将检索在给定时间戳日期注册的汽车,如果时间戳 dateTs(其可选)为空然后它将检索所有汽车。
我认为当前的实现将不起作用,因为如果dateTs 为空,那么它就不能传递给getCars(),它需要Long 类型的值。我应该在哪里以及如何检查dateTs 是否不为空以及如何将相应的值传递给getCars() 并调用适当的方法?
@GetMapping(value = "/get/cars")
public CarList CarController(@Param("dateTs") Optional<Long> dateTs) {
return ResponseEntity.ok(carService.getCars((Long) dateSt.get());
}
服务类方法:
public List<Car> getCars(Long dateSt) {
List<Car> carList;
if(dateSt != null){
carList = carReposistory.retrieveRegisteredCars(dateSt);}
else{
carList = carReposistory.retrieveAllCars();}
return carList;
}
【问题讨论】:
-
null 可以传递给 getCars,因为 Long 是一个对象,你会遇到 long(本机类型)的问题
-
不确定您所说的“长(本机类型)”是什么意思?我必须使用
<Long> dateTs。所以你说没有附加价值的 Long 仍然是一个对象。dateTs是一个可选值,所以如果没有提供值,那么我假设没有值的 Long 对象可以进一步处理和传递。如果 dateSt.get() 为 null,会导致任何问题吗? -
好吧,我建议您阅读 javadocs,docs.oracle.com/javase/8/docs/api/java/util/Optional.html 获取“如果此 Optional 中存在值,则返回该值,否则抛出 NoSuchElementException。”,所以是的,您将抛出异常正如您在一些答案中看到的那样,您可以使用 orElse(null)
标签: java spring api http optional