Java/Spring
Custom Queries with JPA
WebDevLee
2024. 10. 15. 16:37
JPA를 이용한 커스텀 쿼리 작성법에 대해 정리하였습니다.
< Custom Queries with JPA >
Based on how the method is named, Spring Data JPA will automatically generate the “implementation” of the method when your application is compiled.
The naming of the method declarations is extremely important here. The rules for the method names are detailed in the Spring documentation
JPA Query Methods :: Spring Data JPA
As of Spring Data JPA release 1.4, we support the usage of restricted SpEL template expressions in manually defined queries that are defined with @Query. Upon the query being run, these expressions are evaluated against a predefined set of variables. Sprin
docs.spring.io
Example)
public interface PersonRepository extends CrudRepository<Person, Integer> {
// this declaration is all we need!
List<Person> findByEyeColor(String eyeColor);
}
@GetMapping("/people/search")
public List<Person> searchPeople(
@RequestParam(name = "eyeColor", required = false) String eyeColor
) {
if (eyeColor != null) {
return this.personRepository.findByEyeColor(eyeColor)
} else {
return new ArrayList<>();
}
}
: This capability is extremely powerful, as it allows developers to create complex queries without even writing the code for them!
< Advanced Custom Queries >
You can get even more advanced using And queries
List<Person> findByEyeColorAndAgeLessThan(String eyeColor, Integer age);
@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<>();
}
}