DEVLOG

[JPA] 페이징 본문

Spring Boot/JPA

[JPA] 페이징

BINTHEWORLD 2022. 6. 27. 13:57

Pageable 인터페이스

SpringBoot에서는 Pageable 인터페이스로 비교적 간단하게 페이징을 구현할 수 있다.
Pageable 인터페이스는 페이징을 구현할 때 필요한 값들을 편하게 구할 수 있는 메소드들을 추상화 시켜놓았기 때문이다. 그러므로 Controller 에서 Pageable 인터페이스 타입으로 파라미터를 받으면 된다.

Page 인터페이스

Page 인터페이스도 내부 메소드를 보면 페이징을 구현할 때 필요한 값들을 getTotalPages(), getTotalElements()와 같은 메소드로 추상화 시켜놓은 인터페이스임을 알 수 있다.

예제 DummyControllerTest.java

@RestController
public class DummyControllerTest {
	
	@Autowired
	private UserRepository userRepository;
	
	// http://localhost:8000/blog/dummy/user
	@GetMapping("/dummy/users")
	public List<User> list() {
		return userRepository.findAll();
	}
	
	// 한 페이지당 2건의 데이터(size=2)를 리턴받아 볼 예정
	@GetMapping("/dummy/user")
	public List<User> pageList(@PageableDefault(size=2/*페이지당 2개씩*/, sort="id", direction=Sort.Direction.DESC) Pageable pageable) {
		Page<User> pagingUser = userRepository.findAll(pageable);
		
//		if(pagingUser.isLast()) { // 분기가능
//			
//		}

		List<User> users = pagingUser.getContent();
		return users;
	}
}

'Spring Boot > JPA' 카테고리의 다른 글

[JPA] not null constraint violation 에러  (0) 2022.11.16
[JPA] open-in-view  (0) 2022.06.30
[JPA] UPDATE  (0) 2022.06.27
[JPA] SELECT  (0) 2022.06.27
[JPA] 연관관계 매핑  (0) 2022.06.25
Comments