Home > Back-end >  Springboot/Spring JPA - Controller with multiple GetMapping methods
Springboot/Spring JPA - Controller with multiple GetMapping methods

Time:10-30

I have a situation where I have several SQL queries getting data from same table, just filtering differently. For example:

SELECT * FROM CAR WHERE CAR_NUM <> 111    

SELECT * FROM CAR WHERE SELL_DATE BETWEEN '2020-01-01' AND '2021-12-15'
    
SELECT * FROM CAR WHERE ...

...

...

I have about 10 queries, each against CAR data table but with different WHERE clause filtering data in a different way.

I implemented CarController, CarService, CarRepository using Spring JPA. My Controller currently has 2 @GetMapping methods and I am planning to add more @GetMapping methods to cover all SQL queries I have above

@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
      List<CarResponse> cars = carRepository.getAllCarsSoldBetweenDates(dateRange.get("startDate"), dateRange.get("endDate"));
      return cars;
    }

}

However, I get error like:

java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'carController' method com.me.carController#getAllCarsSoldBetweenDates(Map) to {GET [/cars], produces [application/json]}: There is already 'carController' bean method com.me.carController#getAllCars() mapped.

I am not sure what is that I am missing?

CodePudding user response:

You specified @GetMapping() to both of your methods. This binds both methods with one endpoint /cars. Each controller method should have unique mapping associated with it.

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

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

  • Related