BackEnd/Spring

[Spring JPA] Spring Data JPA의 쿼리 메소드 작성 규칙

ryuneng 2025. 1. 19. 00:04
반응형

✔️ Spring Data JPA의 쿼리 메소드 작성 규칙

* By의 B는 반드시 대문자로 작성

1. 데이터 조회

find...By... 형식으로 작성


2. 데이터 개수 조회

count...By... 형식으로 작성

  • 반환타입 : Long 값

3. 데이터의 존재 여부 조회

exists...By... 형식으로 작성

  • 반환타입 : boolean 값

4. 데이터 삭제

delete...By... 형식으로 작성


5. 데이터 조회 제한

findFirst...By...
findFirst3...By...
findTop...By...
findTop3...By... 형식으로 작성





➖ Spring Data JPA가 지원하는 키워드

1. Distinct

  • 중복행 제거
  • findDistinctByLastnameAndFirstname(String lastname, String firstname)
    • 아래 쿼리가 실행된다.
      select distinct ...
      from ...
      where lastname = ? and firstname = ?

2. And

  • AND 조건
  • findByLastnameAndFirstname(String lastname, String firstname)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where lastname = ? and firstname = ?

3. Or

  • OR 조건
  • findByLastnameOrFirstname(String lastname, String firstname)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where lastname = ? or firstname = ?

4. Between

  • 범위 조건
  • findByPriceBetween(int min, int max)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where price between ? and ?

5. Lessthan

  • findByPriceLessThan(int price)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where price < ?

6. LessThanEqual

  • findByPriceLessThanEqual(int price)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where price <= ?

7. GreaterThan과 GreaterThanEqual

  • Lessthan과 LessThanEqual방향만 반대

8. After

  • 시간상으로 이후
  • findByStartdateAfter(Date day)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where startdate > ?

9. Before

  • After부호방향만 반대

10. isNull, Null

  • 컬럼값이 null인 것 조회
  • findByManagerIdIsNull()
  • findByManagerIdNull()
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where manager_id is null

11. isNotNull, NotNull

  • 컬럼값이 not null인 것 조회
  • findByManagerIdIsNotNull()
  • findByManagerIdNotNull()
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where manager_id is not null

12. OrderBy

  • findAllOrderByLastnameDesc()
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      order by lastname desc

13. In

  • findByManagerIdIn(Collection<String> lastnames)
    • 아래 쿼리가 실행된다.
      select ...
      from ...
      where lastname in (?, ?, ?)


< 해당 글은 velog에서 이전하며 옮겨온 글로, 가독성이 좋지 않을 수 있는 점 양해 부탁드립니다. >

🔗 velog 버전 보기 : https://velog.io/@ryuneng2/Spring-Spring-Data-JPA의-쿼리-메소드-작성-규칙