하나씩 차근차근
article thumbnail

이번 포스트에서는 question 테이블에 저장된 게시글을 페이징 처리해서 브라우저에 보여주도록 하겠습니다.

 

시작

현재 데이터베이스에 데이터가 2개밖에 없기 때문에 더미데이터를 만들어주겠습니다.

MariaDB [springboot_crud]> delimiter $$
MariaDB [springboot_crud]> drop procedure if exists loopinsert$$
Query OK, 0 rows affected (0.006 sec)

MariaDB [springboot_crud]> create procedure loopinsert()
    -> begin
    -> declare i int default 1;
    -> while i<= 100 do
    -> insert into question(content, create_date, subject)
    -> values(concat('title',i), '2023-01-23 12:43:00', concat('subject',i));
    -> set i = i + 1;
    -> end while;
    -> end $$

위와 같이 더미데이터를 만들어주는 loopinsert 프로시저를 만듭니다.

MariaDB [springboot_crud]> delimiter ;
MariaDB [springboot_crud]> call loopinsert();
Query OK, 100 rows affected (0.067 sec)

다음으로 loopinsert 를 실행시키면 100개의 더미데이터가 만들어집니다.

delimiter 는 문장 입력의 끝을 설정해주는 명령어

이때, delimiter 는 문장의 끝을 설정하는 명령어로 프로시저를 만들때 $$ 로 바꿨던 설정을

다시 delimiter 를 통해 ; 로 바꿔야합니다.

MariaDB [springboot_crud]> select * from question;

select * from question 명령어를 통해 확인해보면 테이블에 데이터가 추가된것을 볼 수 있으며,

브라우저를 통해 페이지에 접속하면 question 테이블에 저장된 데이터들이 출력됩니다.

 

페이징 처리

다음으로 페이징 처리를 해보겠습니다.

먼저 QuestionRepository 에 Pageable 객체를 입력받아 Page<Question> 객체를 리턴하는 findAll 메서드를 작성합니다.

package com.crud.repository;

import java.util.List;

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

import com.crud.model.Question;

public interface QuestionRepository 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 객체는 java.awt.print.Pageable 이 아닌 org.springframework.data.domain.Pageable 에서 import 합니다.

다음으로 QuestionRepository 에서 만든 findAll 메서드를 통해 

QuestionService 에 페이지 번호를 입력받아 해당 페이지의 질문을 리턴하는 메서드를 만듭니다.

package com.crud.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.crud.model.Question;
import com.crud.repository.QuestionRepository;

@Service
public class QuestionService {

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

PageRequest.of(page, 10) 에서 page 는 조회할 페이지 번호를 뜻하며,

다음 인자인 10은 한 페이지에 보여줄 게시물의 개수를 말합니다.

PageRequest.of(조회할 페이지 번호, 한 페이지에 보여줄 게시물 개수)

이때 페이지 번호는 1이 아닌 0이 제일 첫 페이지입니다.

다음으로 QuestionController 에서 기존에 작성한 list 메서드를 아래와 같이 수정합니다.

기존의 list 메서드는 모든 question 데이터를 가져오는 역할을 했다면,

수정한 list 는 page 값을 입력으로 받아 해당 페이지에 있는 question 10개만 보여주는 기능을 합니다.

(만약, page 값이 없을 경우 0을 입력받아 제일 첫 page 를 보여줍니다.)

package com.crud.controller;
...
@Controller
public class QuestionController {
	
	@Autowired
	private QuestionService questionService;

	/*
	@GetMapping("/question/list")
	public String list(Model model) {
		List<Question> questionList = questionService.getList();
		model.addAttribute("questionList", questionList);
		return "question_list";
	}*/
	
	@GetMapping("/question/list")
	public String list(Model model, @RequestParam(value = "page", defaultValue = "0") int page) {
		
		Page<Question> paging = questionService.getList(page);
		model.addAttribute("paging", paging);
		return "question_list";
	}
	...
}

마지막으로 list 메서드에서 question_list 파일로 model 을 통해 paging 변수에 담아서 데이터를 보냈습니다.

기존에는 questionList 변수였지만 paging 으로 수정했기 때문에

question_list 의 반복문 (each) 부분도 paging 으로 바꿔줍니다.

<html layout:decorate="~{layout}">
	...
	<tbody>
		<tr th:each ="question : ${paging}">
			<td th:text="${question.id}"></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>
	...
</html>

 

다음과 같이 localhost:8080/questio/list?page=페이지 번호에서 페이지 번호를 입력하면

각 페이지에 10개의 question 이 출력되는것을 볼 수 있습니다.

 

profile

하나씩 차근차근

@jeehwan_lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!