본문 바로가기
Spring/[Spring]Pagination(페이징)

페이징처리 - 2 (Service,mapper,api,db)

by Ms.Pudding 2022. 1. 10.

프레임워크 : 마이바티스 mybatis

view 템플릿 : 타임리프 thymleaf

 

이제 로직에서 pagingVO를 사용해야 한다.

먼저 @service로 가서 페이징 객체를 사용할 수 있도록 추가해준다.

 
1.@Service

기존 리스트 메소드에 페이지 객체를 넣어준다, 왜냐하면 목록을 보여줄 때, 다음페이지로 갈 때 페이징 메소드를 사용해야하기 떄문에 같이 가지고 가준다.

public List<BoardVO> getList(PagingVO page) throws Excetption{
	return mapper.getList(page);
}

저 메소드 위에 , 전체 게시글 수 메소드 만들어줌 , 전체 게시글 수만

구하는 거라서 따로 파라메터 안씀 .. 

전체 게시글 게수를 구하는 이유는 , 페이지 설정할 때 api에서 전체게시글 수 확인이 필요하기 때문

 public int getListCount() throws Exception{
        return this.mapper.getListCount();
    }

 

 

2.@mapper

이제 mapper로 가서

전체 게시물 수 db에 연동해줌

public int getListCount() throws Excpetion;
    public List<BoardVO> getBoardList(PagingVO page) throws Exception;

 

3.데이터 변동을 확인하는 api에서 getListCount()를 추가해준다.

getListCount()가 무엇을 받는 것인지 메소드 아직 안만들었음

api로 가서 만들어준다

pagingvo를 추가해서 코드를 살짝 수정해준다.


@Restcontroller
public class BoardApiController{
	private final BoardService service;
	@GetMapping("/api/board/list")
    Map<String, Object> resultMap = new HashMap<String, Object>();
	public Map<String,Object> getList(@RequestParam int currentPage){

	try{
		PagingVO page = new PagingVO();
       // service에서 쓰는 getListCount()는 totalCount 전체 게시물 수
       int totalCount = service.getListCount();
		page.setTotalCount(totalCount);
		page.setCurrentPage(currentPage);
		List<BoardVO> list = service.getList(page);
        
        //이따가 boardlist.html 자바 스크립트에서 쓸거임 
        	resultMap.put("data",list);
		resultMap.put("pager",page);
		
	}catch(Exception e){
		e.printStackTrace();
		}
	return resultMap;
	}

}

참고로 requestParam을 쓰면

/api/board/list?=currentPage=1 이런식으로 검색하면 페이지 1쪽에 있는것이 나옴

 

3.boardmapper.xml

BoardMapper가서 service에서 만든 getListCount를 db랑 직접 연동해줌

<select id = "getListCount" parameterType = "com.board.web.vo.board.pagingVO' resultType = "int">
	select count(*)
	from board
</select>

list부분도 살짝 수정해보자

 

<select id = "getList" resultType="com.board.web.vo.board.BoardVO">
    select board_no,
            title,
            content,
            writer,
            date_format(reg_date, '%Y-%m-%d %H:%i:%s') as regDate
    from board
            order by reg_date desc
            LIMIT #{startRow}, #{COUNT_PER_PAGE}
</select>

내림차 순으로 date를 정렬 (고->저) 최신글부터 보임

Limit은 페이지 시작 게시물에서 페이지당 보여주는 게시글 수

 

 

댓글