我有一個情況,我有幾個 SQL 查詢從同一個表中獲取資料,只是過濾方式不同。例如:
SELECT * FROM CAR WHERE CAR_NUM <> 111
SELECT * FROM CAR WHERE SELL_DATE BETWEEN '2020-01-01' AND '2021-12-15' //These are DB2 TIMESTAMP fields (e.g. '2021-12-15 12:45:33')
SELECT * FROM CAR WHERE ...
...
...
我有大約 10 個查詢,每個查詢都針對CAR資料表,但使用不同的WHERE子句以不同的方式過濾資料。
我實作了CarController,CarService,CarRepository使用Spring JPA。我的控制器目前有 2 個@GetMapping方法,我計劃添加更多@GetMapping方法來涵蓋我上面的所有 SQL 查詢
@RestController
@RequestMapping("/cars")
public class CarController {
@GetMapping
public List<CarResponse> getAllCars() {
// handle 1st query above and return all cars except one with CAR_NUM=111
List<CarResponse> cars = carRepository.getAllCarsExceptTrippleOne();
return cars;
}
@GetMapping
public List<CarResponse> getAllCarsSoldBetweenDates(@RequestParam Map<Date, Date> dateRange) {
// handle 2nd query above and return all cars sold btw 2 dates. My table holds DB2 TIMESTAMP fields.
List<CarResponse> cars = carRepository.getAllCarsSoldBetweenDates(dateRange.get("startDate"), dateRange.get("endDate"));
return cars;
}
}
但是,我收到如下錯誤:
java.lang.IllegalStateException:不明確的映射。無法將 'carController' 方法 com.me.carController#getAllCarsSoldBetweenDates(Map) 映射到 {GET [/cars],產生 [application/json]}:已經映射了 'carController' bean 方法 com.me.carController#getAllCars() .
我不確定我錯過了什么?
uj5u.com熱心網友回復:
您指定@GetMapping()了兩種方法。這將兩種方法與一個端點系結/cars。每個控制器方法都應該有與之關聯的唯一映射。
@GetMapping
public List<CarResponse> getAllCars() {}
@GetMapping("/soldbetween")
public List<CarResponse> getAllCarsSoldBetweenDates(@RequestParam Map<Date, Date> dateRange) {}
uj5u.com熱心網友回復:
你需要告訴 springGET當你想要獲得所有汽車時呼叫哪個映射,以及當你想要在日期之間出售汽車時使用哪個映射。
不理會第一個,將第二個方法更改為如下所示:
@GetMapping("/sold/{startDate}/{endDate}")
public List<CarResponse> getAllCarsSoldBetweenDates(@PathVariable Long startDate, @PathVariable Long endDate) {
// do validation of the variables, if variables cannot be converted to dates or something
try{
Date startDateObj = new Date(startDate);
Date endDateObj = new Date(endDate);
// handle 2nd query above and return all cars sold btw 2 dates
List<CarResponse> cars = carRepository.getAllCarsSoldBetweenDates(startDateObj, endDateObj);
return cars;
}catch( Exception e ){
// .. handle exception and return empty list?
return Collections.emptyList();
}
}
然后,要呼叫此方法,您可以通過呼叫服務器并傳遞引數來呼叫,例如:
https://<server>:<port>/cars/sold/<startDateAsLong>/<endDateAsLong>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344087.html
