커뮤니티 프로젝트

좋아요 List up 구현

쭈녁 2022. 12. 13. 17:53

인기글 홈 화면에 LIST-UP 해보았다.

 

PostRepository

@Repository
@Transactional
public class PostQueryPostRepository {


    private final EntityManager em;
    private final JPAQueryFactory query;
    public PostQueryPostRepository(EntityManager em) {
        this.em = em;
        this.query = new JPAQueryFactory(em);
    }
   
    public List<Post> hotPost() {
        List<Post> hotPosts = query
                .select(post)
                .from(post)
                .orderBy(post.heartCount.desc())
                .offset(0)
                .limit(5)
                .fetch();
        return hotPosts;
    }

QueryDSL을 활용하여 작성하였다.

 

쿼리문은 아래와 같다.

  • .select(post) : post 전체를 가지고 올것임으로 post를 넣어주었다.
  • .form(post) : post테이블에서 가져올 것임으로 form post 설정
  • .orderby(post.heartCount.desc()) : Post객체의 heratCount의 개수에 따라 내림차순 정렬하였다.
  • .offset(0) : 시작하는 인덱스 번호를 지정
  • .limit : 5개의 인기글을 보여줄 것임으로 5로 설정하였다.

 

PostService

@Service
@Repository
@RequiredArgsConstructor
@Transactional
public class PostService {
    private final PostQueryPostRepository postQueryPostRepository;
    
	public List<Post> top5Post() {
    	return postQueryPostRepository.hotPost();
	}

서비스에서 Repository에서 5개의 게시물을 쿼리문을 통해 가져오도록 구현하였다.

 

HomeController

@Controller
@RequiredArgsConstructor
@Slf4j
public class HomeController {
    private final MemberRepository memberRepository;
    private final PostService postService;

    @GetMapping("/")
    public String loginHome(@Login Member member, Model model, @AuthenticationPrincipal PrincipalDetail principalDetail) {
        List<Post> topPosts = postService.top5Post();
        model.addAttribute("topPosts", topPosts);
        if (principalDetail != null) {
            Member principalDetailMember = memberRepository.findById(principalDetail.getMember().getId()).orElseThrow();

            model.addAttribute("member", member);
            model.addAttribute("principalDetailMember", principalDetailMember);
            return "loginHome";
        }
        return "loginHome";
    }
}

HomeController에서 메인페이지로 접근했을때

postService.top5Post();를 호출하여 리스트에 넣어주고

해당 변수 (topPosts)를 모델로 등록하여 클라이언트 단에서 받을 수 있게 설정하였다.

 

@AuthenticationPrincipal을 통해 시큐리티로 로그인한 Member에 대한 상세 정보를 가져오게 하였다.

로그인이 되어있지 않으면 principalDetail은 null값을 반환하고 때문에 로그인 되었을 때 -> if(principalDetail!=null)일 때 해당 Member를 Model로 넣어주도록 코드를 작성하였다.

 

그 후 front단에서 리스트를 반복문으로 가져오도록 작성하였다. 아래 loginHome.html 참고.

 

위와 같이 설정한 이유는 로그인 하지 않은 사용자에게는 좋아요 표기한 게시물이 표기되지 않게 하기 위함이다. 

 

loginHome.html

<div class="col" >
  <h3>내가 저장한 게시물</h3>
    <div class="col" sec:authorize="!isAuthenticated()">
      로그인을 해주세요
    </div>
    <div class="col" sec:authorize="isAuthenticated()">
      <table class="table">
      <thead>
      <tr>
        <th>제목</th>
        <th></th>

      </tr>
      </thead>
      <tbody>
        <tr th:each="hearts : ${principalDetailMember.hearts}">
            <td th:text="${hearts.post.title}">
              </td>
          <td><button class="badge-primary float-end" th:onclick="|location.href='@{/post/{postId}(postId=${hearts.post.id})}'|"
                      type="button">보러가기
          </button></td>
        </tr>
      </tbody>
      </table>
    </div>
</div>

Controller에서 전달받은 principalDetailMember 로 List<Heart>hearts 를 받아오고 이를 thymleaf 반복문(th:each) 으로 리스트업하였다.

'커뮤니티 프로젝트' 카테고리의 다른 글

이미지 업로드 구현  (0) 2023.01.11
좋아요 기능 개발  (0) 2022.12.12
댓글 삭제 개발  (0) 2022.12.07
댓글 기능 개발 (댓글 저장 부분)  (0) 2022.12.02
회원정보 수정  (0) 2022.11.30