쿼리 메서드(Query Method)

2023. 6. 28. 00:26
🧑🏻‍💻 Springboot 쇼핑몰 프로젝트 with JPA 참고

 

💡 쿼리 메서드(Query Method)?

➡️ Spring Data JPA에서 제공하는 핵심 기능 중 하나로 Repository 인터페이스에 간단한 네이밍 룰을 이용하여 메서드를 작성하면 원하는 쿼리를 실행할 수 있다.

➡️ 쿼리 메서드를 이용할 때 가장 많이 사용하는 문법으로 find 를 사용한다. 엔티티의 이름은 생략 가능하며, By 뒤에는 검색할 때 사용할 변수의 이름을 적어준다.

find + (엔티티 이름) + By + 변수 이름
  • 회원의 이름을 이용하여 데이터를 조회하는 쿼리 메서드를 아래와 같이 적어줄 수 있다.
find(Member)ByName

 

 

✔️ 예시

ItemRepository

  • 엔티티는 생략이 가능하기 때문에 findItemByItemNm 대신 findByItemNm, 매개변수로는 검색할 때 사용할 상품명 변수 넣어준다.

 

상품명 조회를 위한 테스트 클래스

  • ItemRepository 인터페이스에 작성했던 findByItemNm 메서드 호출하여 검색할 상품명을 매개변수로 넣어준다. 
  • 향상된 for문을 순회하여 일치하는 상품명을 찾아 item 객체를 출력한다. 

코드 실행 결과

  • 테스트 코드를 실행하면 콘솔창에 위 그림과 같은 쿼리문이 실행되는 것을 볼 수 있다. WHERE 절에서 item_nm 이 조건으로 걸려 있고 결과적으로 원하는 "테스트상품1" 도 잘 나타났다.

 

하지만 여러 개의 조건을 이용하여 상품을 검색하거나 결과를 정렬해야 하는 경우는 어떻게 처리할까? 
(참고 : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods)
Keyword Sample JPQL snippet
Distinct findDistinctByLastnameAndFirstname select distinct …​ where x.lastname = ?1 and x.firstname = ?2
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is, Equals findByFirstname
findByFirstnameIs
findByFirstnameEquals
… where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull, Null findByAge(Is)Null … where x.age is null
IsNotNull, NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstname) = UPPER(?1)

'Spring > JPA' 카테고리의 다른 글

@Query 어노테이션  (0) 2023.08.15
기본키(Primary Key) 매핑 - @Id, @GeneratedValue  (0) 2023.07.29
JPA?  (0) 2023.06.01

BELATED ARTICLES

more