Limited JPA data retrieval

Viewed 36

Here is simplified extract from project. CarController class is supposed to return collection of cars from JPA repository. I am passing parameters to CarService class retrieveAllCars() method that will process DB data extraction.

@RestController
public class CarController {
    private CarService = carService;

    @GetMapping("/cars")
    public ResponseEntity getCars(@Param("brandName") Optional<String> brandName,
                                  @Param("type") Optional<String> type){
    return ResponseEntity.ok(carService.retrieveAllCars(brandName, type)); 
    }
}

@Service
public class CarService {
    private CarRepository carRepository;

    public List<Car> retrieveAllCars(String brandName, String type){
        List<Car> carList = new ArrayList<>(); 
          
        carList = carRepository.findall();
        return carList;
    }
}

Currently findall() should be finding all cars. Now I want to find only cars with specific properties, using methods parameters brandName and type. What is the best to achieve it? Is there a way to pass those parameters to JPA method to retrieve limited data?

1 Answers

just add to CarRepository the method findByBrandNameAndType(String brandName, String type)

Related