스프링 데이터 JPA 쿼리 메서드
- 메서드 이름으로 쿼리 생성
- 메서드 이름을 분석하여 JPQL 쿼리로 자동 생성
- 종류
- 메서드 이름
- 메서드 이름으로 JPA Named Query 호출
@Query어노테이션을 사용- 레포 인터페이스에 쿼리를 직접 정의함
메서드 이름으로
public interface ItemRepository extends JpaRepository<Item, Long> {
List<Item> findByName(String name);
}@Test
void selectSpringDataJpa() {
List<Item> item = itemRepository.findByName("item1");
System.out.println("item = " + item);
}select i1_0.id,i1_0.name,i1_0.price,i1_0.stock_quantity from item i1_0 where i1_0.name='item1';
item = [Item(id=2, name=item1, price=1000, stockQuantity=1)]메서드 이름으로 만들때 주의
- 규칙 준수
- 메서드 이름을 정해진 규칙을 반드시 지켜야함
- (예:
findBy,GreaterThan,Between등).
- 필드명 변경시 주의!
- 엔티티의 필드명이 변경되면, 관련 메서드의 이름도 함께 변경해야함
- 어플리케이션 컨텍스트가 초기화되는 시점에
- → Data jpa 레포 인터페이스 로드
- → 메서드 이름을 분석해 쿼리 생성
- 메서드 이름이 엔티티의 필드명과 일치하지 않거나 잘못된 규칙으로 작성되는 경우
- 스프링 데이터 JPA 는 해당 쿼리 메서드에 대한 구현을 생성 X → 오류 발생
- 문법
- And / Or
findByLastnameAndFirstname:where x.lastname = ?1 and x.firstname = ?2
findByLastnameOrFirstname:where x.lastname = ?1 or x.firstname = ?2
- Is, Equals
findByFirstname,findByFirstnameIs,findByFirstnameEquals:where x.firstname = ?1
- Between, LessThan, GreaterThan 등
findByStartDateBetween:where x.startDate between ?1 and ?2
findByAgeLessThan:where x.age < ?1
findByAgeGreaterThan:where x.age > ?1
- Null 관련
findByAgeIsNull:where x.age is null
findByAgeIsNotNull,findByAgeNotNull:where x.age is not null
- Like, NotLike
findByFirstnameLike:where x.firstname like ?1
findByFirstnameNotLike:where x.firstname not like ?1
- StartingWith, EndingWith, Containing
findByFirstnameStartingWith:where x.firstname like ?1(parameter에%가 앞에 붙음)
findByFirstnameEndingWith:where x.firstname like ?1(parameter에%가 뒤에 붙음)
findByFirstnameContaining:where x.firstname like ?1(parameter 양쪽에%가 감싸짐)
- OrderBy, Not, In
findByAgeOrderByLastnameDesc:where x.age = ?1 order by x.lastname desc
findByLastnameNot:where x.lastname <> ?1
findByAgeIn(Collection ages):where x.age in ?1
findByAgeNotIn(Collection ages):where x.age not in ?1
- 기타 키워드
TRUE,FALSE:findByActiveTrue(),findByActiveFalse()
IgnoreCase:findByFirstnameIgnoreCase:where UPPER(x.firstname) = UPPER(?1)
- And / Or
Uploaded by N2T
'자바 > QueryDsl' 카테고리의 다른 글
| [QueryDSL] 프로젝션과 결과의 반환 (0) | 2023.11.15 |
|---|---|
| [DataJpa] 데이터 JPA 공통 인터페이스 (0) | 2023.11.15 |
| [DataJpa] Named Query (0) | 2023.11.15 |
| [DataJpa] Named Query (0) | 2023.11.15 |
| [QueryDSL] 그룹과 조인 (0) | 2023.11.15 |