메서드명으로 자동으로 SQL을 생성하는 기능
패턴: find[First|Top(N)]By[컬럼명][조건]
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 ?
findByQtyIsNull() // where qty is null
findByQtyIsNotNull() // where qty is not null
findByColorIn(List<String>) // where color in (?, ?, ?)
findByColorNotIn(List<String>) // where color not in (?, ?, ?)
findByNameStartsWith(String) // where name like '?%'
findByNameEndsWith(String) // where name like '%?'
findByNameContains(String) // where name like '%?%'
findByNameLike(String) // where name like ?
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
// 기본
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")
)
);
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";
}
복수 테이블 조인, 집계함수(COUNT, SUM), GROUP BY 등은 불가능 → JPQL이나 Query DSL 필요