Custom Query Advanced SpringBoot

PHOTO EMBED

Thu Dec 22 2022 18:20:46 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka #java #springboot

//Repository
List<Person> findByEyeColorAndAgeLessThan(String eyeColor, Integer age);
//Controller
@GetMapping("/people/search")
public List<Person> searchPeople(
  @RequestParam(name = "eyeColor", required = false) String eyeColor,
  @RequestParam(name = "maxAge", required = false) Integer maxAge 
) {
  if (eyeColor != null && maxAge != null) {
    return this.personRepository.findByEyeColorAndAgeLessThan(eyeColor, maxAge);
  } else if (eyeColor != null) {
    return this.personRepository.findByEyeColor(eyeColor);
  } else if (maxAge != null) {
    return this.personRepository.findByAgeLessThan(maxAge);
  } else {
    return new ArrayList<>();
  }
}
content_copyCOPY