Spring Data JPA 메서드 네이밍 규칙: 자동으로 SQL 생성하기

hidihyeonee·2025년 3월 11일
0

2025.03.11 작성

OS : Window
개발환경: IntelliJ IDEA
개발언어: Java
프레임워크: Spring Boot


메서드 네이밍 규칙

Spring Data JPA는 메서드 이름을 특정 규칙에 맞춰 쓰면 자동으로 쿼리를 생성해줌.

예) findByAccountAccountNumberOrderByCreatedDesc() 로 변경하면 최신 거래부터 순서대로 불러옴

규칙

findBy + [컬럼명] + OrderBy[정렬할 컬럼명] + Desc(내림차순) / Asc(오름차순)
  • 컬럼명은 엔티티 필드 이름 기준으로 사용해야 함.
  • OrderByCreatedDesc → created 기준 내림차순 정렬.
  • JPA가 자동으로 ORDER BY created DESC SQL을 생성.

적용 코드

public interface AccountHistoryRepository extends JpaRepository<AccountHistoryEntity, Integer> {
    // 기존 메서드 → 정렬 추가
    List<AccountHistoryEntity> findByAccountAccountNumberOrderByCreatedDesc(String accountNumber);
}
  • findByAccountAccountNumber() → 특정 계좌 거래 내역 조회
  • OrderByCreatedDesc → created 기준으로 최신순 정렬

실제 SQL 변환

위 JPA 메서드는 다음 SQL과 동일함:

SELECT * 
FROM account_history 
WHERE account_no = ? 
ORDER BY created DESC;

💡 예제 코드

// 특정 유저의 계좌 내역을 최신순으로 가져오기
List<AccountHistoryEntity> findByUserIdxOrderByCreatedDesc(int userIdx);

// 특정 계좌에서 금액이 10,000원 이상인 거래만 가져오기
List<AccountHistoryEntity> findByAccountAccountNumberAndTransferBalanceGreaterThan(String accountNumber, int amount);

못 외울 것 같을 때 꿀팁 🍯

1. 필요할 때 구글링 → "Spring Data JPA 메서드 네이밍 규칙"

2. 자주 쓰는 패턴만 익히기 (findBy, OrderBy, And, Or 등)

3. 헷갈리면 JPQL이나 Native Query로 직접 쿼리 짜기

profile
벨로그 쫌 재밌네?

0개의 댓글