728x90
반응형
SMALL

대량 테스트 데이터 만들기

페이징을 구현하기 위해서는 충분한 데이터가 필요하기 때문에 테스트 프레임워크를 이용한다.

SbbApplicationTests.java

...

@Autowired
private QuestionService questionService;

...

@Test
void testJpa() {
	for(int i=1; i<=300; i++) {
		String subject = String.format("테스트 데이터입니다:[%03d]", i);
		String content = "내용 없음";
		this.questionService.create(subject, content);
	}
}

 

로컬 서버를 중지하고 [Run -> Run As -> Junit Test]로 실행하자.

테스트가 성공하면 다시 로컬 서버를 실행 후 페이지를 확인해보자.
데이터 300개가 생성된 것을 볼 수 있다.

 

페이징 구현하기

페이징을 구현하기 위해 추가로 설치해야 하는 라이브러리는 없다.

JPA 환경 구축 시 설치했던 JPA 관련 라이브러리에 이미 페이징을 위한 패키지들이 들어있기 때문이다.

org.springframework.data.domain.Page: 페이징을 위한 클래스
org.springframework.data.domain.PageRequest: 현재 페이지와 한 페이지에 보여줄 게시물 개수 설정하여 요청하는 클래스
org.springframework.data.domain.Pageable: 페이징을 처리하는 인터페이스

 

위에 말한 객체를 이용하여 페이징을 구현해보자.

/question/QuestionRepository.java

package com.mysite.sbb.question;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface QuestionRepostiory extends JpaRepository<Question, Integer> {
	Question findBySubject(String subject);
	Question findBySubjectAndContent(String subject, String content);
	List<Question> findBySubjectLike(String subject);
	Page<Question> findAll(Pageable pageable);
}

Pageable 객체를 입력받아 Page<Question> 타입 객체를 리턴하는 findAll 메서드를 생성한다.

 

/qeustion/QuestionService.java

...
public Page<Question> getList(int page){
		Pageable pageable = PageRequest.of(page, 10);
		return this.questionRepostiory.findAll(pageable);
}
...

원래 있던 getList 메서드를 위와 같이 변경했다.

원래는 모든 데이터를 가져왔지만 원하는 페이지의 데이터를 10개씩만 가져오도록 수정.

 

이 메서드의 입출력 구조가 바뀌었으므로 컨트롤러의 list메서드에 오류가 생겼을 것이다.

컨트롤러의 메서드도 수정해보자.

/question/QuestionController.java

...
@GetMapping("/list")
public String list(Model model, @RequestParam(value = "page", defaultValue = "0")int page) {
	Page<Question> paging = this.questionService.getList(page);
	model.addAttribute("paging",paging);
	return "question_list";
}
...
localhost:8080/question/list?page=0 과 같이 GET방식으로 요청된 URL에서 page값을 가져오기 위해 list 메서드 매개변수로 @RequestParam(value="page", defaultValue="0")int page가 추가되었다. 만약 page값이 전달되지 않은 경우에는 기본값을 0으로 지정했다..

 

위 컨트롤러에서 model에 questionList 대신 paging으로 전달하기 때문에 템플릿을 변경해야 한다.

/templates/question_list.html

<html layout:decorate="~{layout}">
<div layout:fragment="content" class="container my-3">
<table class="table">
	<thead class="table-dark">
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성일시</th>
		</tr>
	</thead>
	<tbody>
		<tr th:each="question, loop : ${paging}">
			<td th:text="${loop.count}"></td>
			<td>
				<a th:href="@{|/question/detail/${question.id}|}"
				th:text="${question.subject}"></a>
			</td>
			<td th:text="${#temporals.format(question.createDate, 'yyyy-MM-dd HH:mm')}"></td>
		</tr>
	</tbody>
</table>
<a th:href="@{/question/create}" class="btn btn-primary">질문 등록하기</a>
</div>
</html>

th:each문에서 paging으로 변경한 모습

 

localhost:8080/question/list?page=0으로 요청하면 첫 페이지의 10개만 조회된다.

 

page=1로 수정하니 두번째 페이지가 나타나는 것을 볼 수 있다.

 

728x90
반응형
LIST

+ Recent posts