본문 바로가기
[Spring Boot]

[스프링부트] 게시판 조회수 추가하기

by 슬쨩! 2024. 1. 24.

 

  구현 화면

 

 

수정할 부분 요약

Question에 view 컬럼 추가하기

 QuestionService에서 getQuestion 메서드 수정하기

 question_list.html 조회수 텍스트 및 테이블 수정하기

 

 

 

✅ [1단계 : Question에 view 컬럼 추가하기]

@Column(columnDefinition = "integer default 0", nullable = false)

private int view;

 

 

/h2-console 에 접속해서 view 칼럼 생성됐는지 확인 필요

 

✅ [2단계 : QuestionService에서 getQuestion 메서드 수정하기 ]

public Question getQuestion(Integer id) {

Optional<Question> question = this.questionRepository.findById(id);

if (question.isPresent()) {

//조회수

Question question1=question.get();

question1.setView(question1.getView()+1);

this.questionRepository.save(question1);

//조회수 끝

return question1;

} else {

throw new DataNotFoundException("question not found");

}

}

 

getQuestion 메서드에서는 주어진 id에 해당하는 질문을 가져오고,

가져온 질문의 조회수를 1 증가시킨 후 저장하는 것을 수행

 

 

✅ [3단계 : question_list.html 조회수 텍스트 및 테이블 수정하기  ]

 

조회수 텍스트와 테이블에 값을 넣어줌으로 완성