[스프링부트 게시판] 30. 게시판 정렬 기능 구현

2022. 9. 3. 14:36·🚗 Backend Toy Project/스프링 부트 게시판
  • 최신순, 인기순(조회수), 추천순으로 게시판을 정렬하는 기능을 구현해보았습니다.
  • Controller에서 파라미터로 정렬 타입을 전달받고 PageRequest.of 메서드를 사용하여 정렬 방식을 변경하는 식으로 구현하려 하였으나 해당 방법을 사용할 경우 데이터를 제대로 정렬하여 뽑아오지만 페이징이 되지 않는 오류가 발생하여 조금 다른 방법을 사용하였습니다.

📝 RecommendRepository, RecommendService

  • 우선 추천순 정렬을 위해 Repository에 코드를 추가해주었습니다.
package com.cos.blog.repository;

...

public interface RecommendRepository extends JpaRepository<Recommend, Long>{

	...
	
	@Modifying
	@Query("update Board b set b.recommendCount = b.recommendCount + 1 where b.id = :board_id")
	void increaseRecommendCount(Long board_id);
	
	@Modifying
	@Query("update Board b set b.recommendCount = b.recommendCount - 1 where b.id = :board_id")
	void decreaseRecommendCount(Long board_id);
}
  • 이후 Service에서 위에서 추가한 메서드를 사용하여 카운팅 해주었습니다.
package com.cos.blog.service;

...

@RequiredArgsConstructor
@Service
public class RecommendService {

	private final RecommendRepository recommendRepository;
	
	@Transactional
	public void recommend(Long board_id, Long principal_id) {
		recommendRepository.recommend(board_id, principal_id);
		recommendRepository.increaseRecommendCount(board_id);
	}
	
	@Transactional
	public void cancelRecommend(Long board_id, Long principal_id) {
		recommendRepository.cancelRecommend(board_id, principal_id);
		recommendRepository.decreaseRecommendCount(board_id);
	}
}

📝 BoardController

  • Controller에서는 요청되는 경로에 따라 데이터를 알맞게 정렬하여 가져올 수 있도록 구현해주었습니다.
package com.cos.blog.controller;

...

@Controller
@RequiredArgsConstructor
public class BoardController {

	...
	
	@GetMapping("/")
	public String index(Model model, 
			@PageableDefault(size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
			@RequestParam(value = "searchType", defaultValue = "title") String searchType,
			@RequestParam(value = "searchKeyword", defaultValue = "") String searchKeyword) {
		
		if(searchKeyword == null || searchKeyword.isBlank()) {
			model.addAttribute("boards", boardRepository.findAll(pageable));
		}
		
		if(searchType.equals("nickname")) {
			model.addAttribute("boards", boardRepository.findByUserNicknameContaining(searchKeyword, pageable));
		} else {
			model.addAttribute("boards", boardRepository.findByTitleContaining(searchKeyword, pageable));
		}
		
		return "index";
	}
	
	@GetMapping("/board/{id}")
	public String detail(@PathVariable Long id, Model model,
			HttpServletRequest request, HttpServletResponse response,
			@AuthenticationPrincipal PrincipalDetail principal,
			@RequestParam(value = "page", defaultValue = "0") String page,
			@RequestParam(value = "sort", defaultValue = "id") String sort,
			@RequestParam(value = "searchType", defaultValue = "title") String searchType,
			@RequestParam(value = "searchKeyword", defaultValue = "") String searchKeyword) {
		
		model.addAttribute("board", boardService.detail(id, request, response, principal.getUser().getId()));
		model.addAttribute("page", page);
		model.addAttribute("sort", sort);
		model.addAttribute("searchType", searchType);
		model.addAttribute("searchKeyword", searchKeyword);
		
		return "board/detail";
	}
	
	...

📝 index.jsp

  • 마지막으로 View에 Dropdown 엘리먼트를 추가하여 사용자가 클릭할 시에 자동으로 요청을 수행하도록 하였습니다.
<div class="dropdown-menu">
    <a class="dropdown-item" href="/?page=${param.page}&sort=id,DESC&searchType=${param.searchType}&searchKeyword=${param.searchKeyword}">최신순</a>
    <a class="dropdown-item" href="/?page=${param.page}&sort=count,DESC&searchType=${param.searchType}&searchKeyword=${param.searchKeyword}">인기순</a>
    <a class="dropdown-item" href="/?page=${param.page}&sort=recommendCount,DESC&searchType=${param.searchType}&searchKeyword=${param.searchKeyword}">추천순</a>
</div>


 

GitHub - Daegwon-Kim/SpringBoot-JPA-Blog

Contribute to Daegwon-Kim/SpringBoot-JPA-Blog development by creating an account on GitHub.

github.com

 

저작자표시 (새창열림)

'🚗 Backend Toy Project > 스프링 부트 게시판' 카테고리의 다른 글

[스프링부트 게시판] 32. 이전에 봤던 글 표시  (0) 2022.09.17
[스프링부트 게시판] 31. 이전글, 다음글 구현  (0) 2022.09.06
[스프링부트 게시판] 29. 추천 기능 구현  (1) 2022.09.01
[스프링부트 게시판] 28. 게시글 검색 기능 구현  (0) 2022.08.30
[스프링부트 게시판] 27. 게시글 작성일 및 조회수 추가  (0) 2022.07.03
'🚗 Backend Toy Project/스프링 부트 게시판' 카테고리의 다른 글
  • [스프링부트 게시판] 32. 이전에 봤던 글 표시
  • [스프링부트 게시판] 31. 이전글, 다음글 구현
  • [스프링부트 게시판] 29. 추천 기능 구현
  • [스프링부트 게시판] 28. 게시글 검색 기능 구현
Baeg-won
Baeg-won
  • Baeg-won
    좋았다면 추억이고 나빴다면 경험이다.
    Baeg-won
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 🍃 Spring, Spring Boot
        • 스프링 프레임워크 기초
        • 스프링 핵심 원리 - 기본편
        • 자바 ORM 표준 JPA 프로그래밍 - 기본편
        • 스프링 MVC
        • 실전! 스프링 부트와 JPA 활용1 - 웹 애플리..
      • 🥑 Web Technoloy
      • 🚗 Backend Toy Project
        • 스프링 부트 게시판
        • Photogram
        • Baeg-won Clothing Gallery
      • 🥇 Problem Solving
        • Breadth-First Search
        • Depth-First Search
        • Backtracking
        • Simulation
        • Two-pointer
        • Binary Search
        • Greedy
        • Dynamic Programming
        • Minimum Spanning Tree
        • Dijkstra
        • Floyd warshall
      • ☕ Java
        • 명품 자바 에센셜
        • Applications
      • 🍦 JavaScript
        • JavaScript 기초
      • 🐧 Linux
        • 이것이 리눅스다(CentOS 8)
      • 📟 Database
        • 혼자 공부하는 SQL
      • 🧬 Data Structure
      • 🎬 HTML
      • 🎤 Tech Interview
      • 📌 etc
        • Unity 2D Raising Jelly Game
        • C++
        • 영어 쉐도잉
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Baeg-won
[스프링부트 게시판] 30. 게시판 정렬 기능 구현
상단으로

티스토리툴바