JPA 스프링부트 - Query Method, 정렬, 페이징

박지명·2026년 5월 10일

스프링부트

목록 보기
5/10

1. Query Method 개념

메서드명으로 자동으로 SQL을 생성하는 기능

패턴: find[First|Top(N)]By[컬럼명][조건]


2. Query Method 패턴 정리

기본

findByName(String)                  // where name = ?
findByNameAndColor(String, String)  // where name = ? and color = ?
findByColorOrQtyOrPrice(...)        // where color = ? or qty = ? or price = ?

비교 연산자

findByPriceGreaterThan(int)         // where price > ?
findByPriceGreaterThanEqual(int)    // where price >= ?
findByPriceLessThan(int)            // where price < ?
findByPriceBetween(int, int)        // where price between ? and ?

NULL 체크

findByQtyIsNull()                   // where qty is null
findByQtyIsNotNull()                // where qty is not null

IN / NOT IN

findByColorIn(List<String>)         // where color in (?, ?, ?)
findByColorNotIn(List<String>)      // where color not in (?, ?, ?)

LIKE 검색

findByNameStartsWith(String)        // where name like '?%'
findByNameEndsWith(String)          // where name like '%?'
findByNameContains(String)          // where name like '%?%'
findByNameLike(String)              // where name like ?

LIMIT (상단 N개)

findFirstByColor(String)            // select top 1 ... where color = ?
findTop3ByColor(String)             // select top 3 ... where color = ?

정렬

findAllByOrderByNameAsc()           // order by name asc
findByColorOrderByPriceAsc(String)  // where color = ? order by price asc
findAllByOrderByColorAscPriceDesc() // order by color asc, price desc

3. Sort 객체 (동적 정렬)

// 기본
itemRepository.findAll(Sort.by("price"));

// 방향 지정
itemRepository.findAll(Sort.by(Sort.Direction.DESC, "price"));

// 여러 컬럼 (권장)
itemRepository.findAll(
    Sort.by(
        Sort.Order.asc("color"),
        Sort.Order.desc("price")
    )
);

4. 페이징

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;

// 1페이지, 5개씩
PageRequest pageRequest = PageRequest.of(0, 5);  // 페이지번호는 0부터 시작

Page<Item> page = itemRepository.findAll(pageRequest);

// 페이징 정보
page.getNumber()            // 현재 페이지 번호
page.getNumberOfElements()  // 현재 페이지의 엔티티 수
page.getTotalElements()     // 전체 엔티티 수
page.getTotalPages()        // 총 페이지 수
page.getSize()              // 1페이지 크기

페이지 네비 구현

@GetMapping("/list")
public String list(
    @RequestParam(name = "page", defaultValue = "1") Integer page,
    Model model) {
    
    page--;  // 1부터 받아서 0으로 변환
    
    PageRequest pageRequest = PageRequest.of(page, 5);
    Page<Item> list = itemRepository.findAll(pageRequest);
    
    List<ItemDto> dlist = list.stream()
            .map(item -> item.toDto())
            .collect(Collectors.toList());
    
    // 페이지 바 HTML 생성
    String temp = "";
    for(int i = 1; i <= list.getTotalPages(); i++) {
        temp += String.format("<a href=\"/list?page=%d\">%d</a>", i, i);
    }
    
    model.addAttribute("dlist", dlist);
    model.addAttribute("paging", temp);
    
    return "list";
}

5. Query Method 한계

복수 테이블 조인, 집계함수(COUNT, SUM), GROUP BY 등은 불가능 → JPQL이나 Query DSL 필요

0개의 댓글