Spring/JPA
쿼리메소드 페이징처리
개발자 카페
2021. 7. 6. 10:49
728x90
1. 일반버전
예를 들어, 'bno > 0 order by bno desc'라는 조건을 구현한 findByBnoGreaterThanOrderByBnoDesc()
메소드에 Pageable을 적용하면...
public interface BoardRepository extends CrudRepository<Board, Long> {
// bno > ? ORDER BY bno DESC limit ?, ?
public List<Board> findByBnoGreaterThanOrderByBnoDesc(Long bno, Pageable paging);
}
파라미터에 Pageable이 적용되었고, 리턴 타입으로 List<>가 적용되었습니다.
테스트하면...
@Autowired
private BoardRepository repo;
@Test
public void testBnoOrderByPaging() {
// spring boot 2.0.0
Pageable paging = PageRequest.of(0, 10);
// bno가 90보다 큰 데이터를 조회
Collection<Board> results = repo.findByBnoGreaterThanOrderByBnoDesc(0L, paging);
}
Pageable 인터페이스에는 여러 메소드가 존재하기 때문에 이를 구현하는 대신에 PageRequest 클래스를 이용하는것이 편리합니다.
2. PageRequest() 에서 OrderBy도 처리하기
public interface BoardRepository extends CrudRepository<Board, Long> {
public List<Board> findByBnoGreaterThan(Long bno, Pageable paging);
}
@Autowired
private BoardRepository repo;
@Test
public void testBnoPagingSort() {
Pageable paging = PageRequest.of(0, 10, Sort.Direction.ASC, "bno");
Collection<Board> results = repo.findByBnoGreaterThan(0L, paging);
}
결과는 bno값이 1부터 10까지 순서대로 나옵니다.
3. List<T> 대신 Page<T> 사용
public interface BoardRepository extends CrudRepository<Board, Long> {
public Page<Board> findByBnoGreaterThan(Long bno, Pageable paging);
}
@Autowired
private BoardRepository repo;
@Test
public void testBnoPagingSort() {
Pageable paging = PageRequest.of(0, 10, Sort.Direction.ASC, "bno");
Page<Board> results = repo.findByBnoGreaterThan(0L, paging);
System.out.println("PAGE SIZE: " + result.getSize());
System.out.println("TOTAL PAGES: " + result.getTotalPages());
System.out.println("TOTAL COUNT: " + result.getTotalElements());
System.out.println("NEXT: " + result.nextPageable());
}
Page<T>는 단순데이터뿐만아니라, 흔히 웹에서 필요한 데이터들을 추가적으로 처리해 줍니다.
결과는
PAGE SIZE: 10
TOTAL PAGES: 20
TOTAL COUNT: 200
NEXT: Page request [number: 1, size 10, sort: bno: ASC]
728x90