1. Spring Boot에서 mybatis와 페이징 처리하기
mybatis를 사용하여 데이터베이스와 연동하고, 페이징 처리를 할 수 있습니다.
mybatis에서는 RowBouds 클래스를 사용하여 페이징 처리를 합니다.
예를들어, 다음과 같이 UserMapper 인터페이스를 작성할 수 있습니다.
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findAll(@Param("offset") int offset, @Param("limit") int limit);
int countAll();
}
이제 UserController에서 UserMapper를 주입받아 페이징 처리를 할 수 있습니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users")
public List<User> getUsers(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
int offset = page * size;
int limit = size;
return userMapper.findAll(offset, limit);
}
@GetMapping("/users/count")
public int countUsers() {
return userMapper.countAll();
}
}
위의 코드에서는 /users 엔드포인트로 GET 요청을 받으면, page와 size 파라미터를 받아서 offset과 limit 값을 계산하고, UserMapper의 findAll 메소드를 호출하여 페이지 처리된 User 엔티티 리스트를 반환 합니다. /users/count 엔드포인트로 GET 요청을 받으면, 전체 User 엔티티 개수를 반환합니다.
2. React에서 페이징 처리하기
React 에서는 react-paginate 라이브러리를 사용하여 페이징 처리를 할 수 있습니다. 이 라이브러리는 페이지 링크를 렌더링하고, 페이지 변경 이벤트를 처리하는 컴포넌트를 제공합니다.
먼저, react-paginate를 설치합니다.
npm install react-paginate --save
그리고, 다음과 같이 Pagination 컴포넌트를 작성할 수 있습니다.
import React, { useState, useEffect } from 'react';
import ReactPaginate from 'react-paginate';
function Pagination() {
const [users, setUsers] = useState([]);
const [pageCount, setPageCount] = useState(0);
const [currentPage, setCurrentPage] = useState(0);
// API에서 데이터를 가져오는 useEffect
useEffect(() => {
const fetchUsers = async () => {
const response = await fetch(`/users?page=${currentPage}`);
const data = await response.json();
setUsers(data);
};
fetchUsers();
}, [currentPage]);
// 전체 페이지 수를 가져오는 useEffect
useEffect(() => {
const fetchCount = async () => {
const response = await fetch('/users/count');
const data = await response.json();
setPageCount(Math.ceil(data / 10)); // 페이지 당 10개씩 보여주기로 가정
};
fetchCount();
}, []);
return (
<div>
{/* 유저 리스트를 출력하는 부분 */}
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
{/* 페이지 링크를 출력하는 부분 */}
<ReactPaginate
pageCount={pageCount}
onPageChange={({ selected }) => setCurrentPage(selected)}
containerClassName={'pagination'}
activeClassName={'active'}
previousLabel="<"
nextLabel=">"
/>
</div>
);
}
export default Pagination;
위의 코드에서, ReactPaginate 컴포넌트는 다음과 같은 props를 받습니다.
- pageCount : 전체 페이지 수
- onPageChange: 페이지 변경 이벤트 핸들러
- containerClassName: 페이지 링크를 감싸는 div 요소의 클래스 이름
- activeClassName: 현재 선택된 페이지 링크의 클래스 이름
- previousLabel : 이전페이지 버튼의 TEXT 지정
- nextLabel: 다음페이지 버튼의 TEXT 지정
3. CSS 스타일링
Pagination 컴포넌트에서 출력되는 페이지 링크는 CSS 스타일링으로 꾸밀 수 있습니다. 아래는 예시입니다.
.pagination {
display: flex;
justify-content: center;
margin-top: 1rem;
}
.pagination li {
list-style: none;
margin-right: 0.5rem;
cursor: pointer;
}
.pagination .active {
font-weight: bold;
}
위의 CSS 코드에서는 페이지 링크를 중앙 정렬하고, 선택된 페이지 링크를 굵은 글씨체로 표시하도록 설정했습니다.
* 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
'IT > Spring Boot' 카테고리의 다른 글
[Exception] 스프링 전역 예외 처리 방법 - (RestControllerAdvice, ExceptionHandler) (0) | 2023.02.09 |
---|