[Java+SpringBoot+JPA] 테이블 조인 / 댓글 수정 기능

2024. 1. 12. 16:15Pratice/CRUD

반응형

 

 

 

[Java+SpringBoot+JPA] 테이블 조인을 활용한 댓글 기능(1)

🟢 Constant 훈련기관 enum 열거형으로 설정 public enum StudyRole { A("우리인재개발원"), B("더조은아카데미"), C("그린컴퓨터"), D("직업전문학원"); private String description; StudyRole(String description) { this.descripti

dalhyehye.tistory.com

 

[Java+SpringBoot+JPA] 테이블 조인을 활용한 댓글 기능+좋아요/싫어요(2)

[Java+SpringBoot+JPA] 테이블 조인을 활용한 댓글 기능(1) 🟢 Constant 훈련기관 enum 열거형으로 설정 public enum StudyRole { A("우리인재개발원"), B("더조은아카데미"), C("그린컴퓨터"), D("직업전문학원"); priva

dalhyehye.tistory.com

 


 

 

🟢 CommentService

▪️ commentDTO.getCommentId()로부터 수정 대상인 댓글의 ID 얻기

▪️ commentDTO.getSid()로부터 해당 댓글이 속한 부모 게시글의 ID를 얻기

▪️ 수정 대상 댓글의 ID와 부모 게시글 정보를 이용하여 매핑된 update를 저장

@Service
@Transactional
@RequiredArgsConstructor
public class CommentService {

  private final StudyRepository studyRepository;
  private final CommentRepositroty commentRepositroty;
  private final ModelMapper modelMapper = new ModelMapper();


  //댓글 수정(게시글 번호, 댓글 내용)
  public void update(CommentDTO commentDTO) throws Exception {

    Integer commentId = commentDTO.getCommentId();

    //댓글조회(확인)
    Optional<CommentEntity> read = commentRepositroty.findById(commentId);
    //오류체크
    CommentEntity commentEntity = read.orElseThrow();

    //댓글에 해당하는 부모 게시글 정보(확인)
    Optional<StudyEntity> data = studyRepository.findById(commentDTO.getSid());
    StudyEntity studyEntity = data.orElseThrow();

    CommentEntity update = modelMapper.map(commentDTO, CommentEntity.class);
    //확인된 댓글번호로 재저장
    update.setCommentId(commentEntity.getCommentId());
    //연관 관계 확인을 위해서 부모 게시글 정보를 저장
    update.setStudyEntity(studyEntity);

    commentRepositroty.save(update);

  }


  public CommentDTO getCommentById(Integer commentId) throws Exception {

    Optional<CommentEntity> commentEntityOptional = commentRepositroty.findById(commentId);

    CommentEntity commentEntity = commentEntityOptional.orElseThrow(() -> new Exception("댓글을 찾을 수 없습니다."));

    return modelMapper.map(commentEntity, CommentDTO.class);

  }
  
}

 

 

🟢 Comment Controller

▪️  댓글 수정 후에 해당 게시글의 상세 페이지로 리다이렉트

@Controller
@RequiredArgsConstructor
public class CommentController {
  
  private final CommentService commentService;


  // 댓글 수정 후 리다이렉트 주소 생성
  public String generateStudyDetailUrl(Integer studyId) {

    return "redirect:/studydetail?sid=" + studyId;

  }

  // 댓글 수정 화면으로 이동
  @GetMapping("/commentupdate")
  public String editCommentForm(@RequestParam("commentId") Integer commentId, Model model) {
    try {
      // commentId를 사용하여 댓글 정보를 가져와서 모델에 추가
      CommentDTO commentDTO = commentService.getCommentById(commentId);
      model.addAttribute("commentDTO", commentDTO);
      return generateStudyDetailUrl(commentDTO.getSid()); // 리다이렉트 주소 생성
    } catch (Exception e) {
      // 오류 처리
      // 적절한 오류 처리 로직 추가
      return "errorPage";
    }
  }

  // 댓글 수정 처리
  @PostMapping("/commentupdate")
  public String editComment(@ModelAttribute CommentDTO commentDTO) {
    try {
      // 댓글 서비스에서 댓글 수정 메소드 호출
      commentService.update(commentDTO);
      // 수정이 완료되면 해당 상세페이지로 리다이렉트
      return generateStudyDetailUrl(commentDTO.getSid()); // 리다이렉트 주소 생성
    } catch (Exception e) {
      // 오류 처리
      // 적절한 오류 처리 로직 추가
      return "errorPage";
    }
  }

}

 

 

 

 

 

 


 

🟢 detail.html

▪️ 수정하기 버튼 → Modal 활용

<button type="button" class="btn btn-primary" data-bs-toggle="modal" th:data-bs-target="'#myModal-' + ${data.commentId}">수정</button>

 

 

▪️ Modal 활용하여 댓글 수정하기

              <form th:action="@{/commentupdate(sid=${studyDTO.sid}, commentId=${data.commentId})}" method="post" th:object="${commentDTO}">  <!-- 댓글 수정 Modal -->
                <div class="modal" th:id="'myModal-' + ${data.commentId}">
                  <div class="modal-dialog">
                    <div class="modal-content">

                      <!-- Modal Header -->
                      <div class="modal-header">
                        <h4 class="modal-title">댓글 수정</h4>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                      </div>

                      <!-- Modal body -->
                      <div class="modal-body">
                        <!-- 기존 댓글 내용 표시 -->
                        <textarea class="form-control" rows="3" id="comment" name="comment" th:text="${data.comment}"></textarea>
                      </div>

                      <!-- Modal footer -->
                      <div class="modal-footer">
                        <button type="submit" class="btn btn-danger" data-bs-dismiss="modal">수정하기</button>
                      </div>

                    </div>
                  </div>
                </div>
              </form>
반응형