스프링 데이터 JPA 레퍼런스
Spring Data Jpa Query maker
쿼리 빌더 메커니즘은 스프링 데이터 리파지토리 인프라스트럭쳐로 짜여져, 리파지토리의 엔티티들에 맞는 쿼리들을 만들어내는 데 유용합니다. 이 메커니즘은 find…By, read…By, query…By, count…By, 와 get…By같은 접두어들을 메소드에서 떼어내고 나머지부분을 파싱하기 시작합니다. 다음 소개하는 절은 Distinct(쿼리가 생성될지 결정하는 flag를 설정)같은 더 깊은 표현을 포함하고 있습니다. 그러나 처음의 By는 실제 크리테리아의 시작을 가리키는 구별자로 동작합니다. 기본레벨에서 당신은 엔티티의 속성을 결정할 조건을 정의할 수 있으며, 그것들을 And 와 Or로 연결할 수 있습니다.
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
// Enabling ignoring case for an individual property
List<Person> findByLastnameIgnoreCase(String lastname);
// Enabling ignoring case for all suitable properties
List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);
// Enabling static ORDER BY for a query
List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}
메소드에 파싱된 실제 결과는 쿼리를 생성하는 데이터베이스에 따라 다르지만, 생각해볼만한 일반적인 것들이 있습니다.
-
이 표현은 보통 속성을 순회하며(영어 오타인듯?) 연결될 수 있는 연산자와 함께 조합됩니다. AND 나 OR같은 표현과 함께 속성을 조합할 수 있습니다. 당신은 또한 Between, LessThan, GreaterThan, Like같은 연산자의 지원을 받을 수 있습니다. 이러한 지원되는 연산자는 데이터스토어에 따라 다를 수 있으니, 해당 레퍼런스 문서에 적절한 부분을 참고해보세요.
-
메소드파서는 code>IgnoreCase에 대한 독립적인 flag 속성설정을 지원하며 예를 들자면 findByLastnameIgnoreCase(…)같은 것이 되거나 findByLastnameAndFirstnameAllIgnoreCase(…)같이 모든 String인스턴스에서도 지원을 할 수 있습니다. 이 부분도 저장소에 따라 다를 수 있으니 해당 저장소 레퍼런스 문서를 참조하세요
-
당신은 정적 순서를 OrderBy절을 추가하여 쿼리메소드의 정렬 방향을 정할 수 있습니다. Asc 나 Desc 로 말이죠.. 동적 정렬을 지원하는 쿼리를 만들기 위해 특별 파라미터 핸들링를 보시기 바랍니다.
쿼리메소드의 결과는 first나 top를 통해서 제한될 수 있으며 바꿔 쓸수 있습니다. 선택적인 숫자값이 top/first 로 추가되어 반환될 최대 결과 크기를 명시할 수 있습니다. 만약 숫자가 무시하면 1로 가정합니다.
User findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
Slice<User> findTop3ByLastname(String lastname, Pageable pageable);
List<User> findFirst10ByLastname(String lastname, Sort sort);
List<User> findTop10ByLastname(String lastname, Pageable pageable);
Limiting 표현은 또한 Distinct키워드를 지원합니다. 또한 결과 셋이 하나의 인스턴스로 제한된 쿼리들을 위해 결과를 Optional로 포장(wrapping)하는 것도 지원됩니다 .
표 4. 메소드 이름 안에서 지원되는 키워드들KeywordSampleJPQL snippet
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 | findByAgeIsNull | … 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> age) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
between 사용법 (가능한 between 조회는 쿼리에 마지막 조건문으로 쓰는게 가독성에 좋을듯)
//between
List<LiveBaseballScore> findByLatestUpdateBetween(Date start, Date end);
//and between
List<LiveBaseballScore> findBySportsIdAndStartDatetimeBetween(String sportsid,Date start, Date end);
JPA Query Builder (Maker)
2022.07.24 - [개발툴] - 스프링 데이터 JPA 레퍼런스 번역 쿼리 빌더
스프링 데이터 JPA 레퍼런스 번역 쿼리 빌더
스프링 데이터 JPA 레퍼런스 번역 쿼리 만들기 Spring Data Jpa Query maker 메소드 이름 안에서 지원되는 키워드들KeywordSampleJPQL snippet And findByLastnameAndFirstname … where x.lastname = ?1 an..
codingfox.tistory.com
'개발툴' 카테고리의 다른 글
픽픽, picpick, 이미지 캡처 프로그램 소개 (4) | 2023.09.02 |
---|---|
오라클 SQL 실행을 위한 mybats 마이바티스 param 변환 쿼리문 파라미터 #{param1} 를 :param1 로 변경 (0) | 2022.07.27 |
스프링 데이터 JPA 레퍼런스 번역 쿼리 빌더 (0) | 2022.07.24 |
문자끝 콤마 , 따옴표 붙이기 오라클 IN 파라미터 쿼리 파라미터 (0) | 2022.07.23 |
문자에 더블 따옴표 붙이기, 문자에 싱글 따옴표 붙이기 (0) | 2022.07.23 |