首页 > 解决方案 > Springboot/Spring JPA - 具有多个 GetMapping 方法的控制器

问题描述

我有一种情况,我有几个 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的子句以不同的方式过滤数据。

我使用 Spring JPA实现了CarController, CarServiceCarRepository我的控制器目前有 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() .

我不确定我错过了什么?

标签: spring-bootspring-data-jpa

解决方案


您指定@GetMapping()了两种方法。这将两种方法与一个端点绑定/cars。每个控制器方法都应该有与之关联的唯一映射。

@GetMapping
public List<CarResponse> getAllCars() {}

@GetMapping("/soldbetween")
public List<CarResponse> getAllCarsSoldBetweenDates(@RequestParam Map<Date, Date> dateRange) {}


推荐阅读