[Java+SpringBoot+JPA] 테이블 조인 / 댓글 수정 기능
2024. 1. 12. 16:15ㆍPratice/CRUD
반응형
🟢 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>
반응형
'Pratice > CRUD' 카테고리의 다른 글
[Java+SpringBoot+JPA] 테이블 조인을 활용한 댓글 기능+좋아요/싫어요(2) (1) | 2024.01.11 |
---|---|
[Java+SpringBoot+JPA] 테이블 조인을 활용한 댓글 기능(1) (1) | 2024.01.11 |
[Java+SpringBoot+JPA] 이미지 삽입을 활용한 게시판 만들기 (1) | 2024.01.09 |
[Java+SpringBoot+JPA] To do List 게시판 만들기 (시작일/마감일 설정) (1) | 2024.01.09 |
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (6) 조회수 증가 기능 (0) | 2024.01.02 |