구현해야 할 기능 : 게시물의 댓글을 삭제하면 DB에 게시판 테이블에 댓글 갯수를 하나 감소 처리를 해주고, 댓글 테이블에서는 해당 댓글을 삭제 처리를 해줘야한다.
📝문제가 발생한 코드
CommentService클래스
// 댓글 삭제
public int remove(Integer cno, Integer bno, String commenter) throws Exception {
int rowCnt = boardDao.updateCommentCnt(bno,-1); //게시판 댓글 갯수도 -1 하나 감소 처리
commentDao.delete(cno, commenter); // 댓글을 삭제한다
}
처음에는 이렇게 작업을 처리해 주었다 remove()가 호출되면 2개의 작업을 수행해서 게시판의 댓글 갯수를 하나 감소하고, 댓글을 삭제하는 작업으로 구현했다. 처음에는 이렇게 구현해도 문제가 없었다. 하지만 작업을 처리하던도중 예외가 발생함으로써 내가 생각했던 데이터베이스의 결과가 일관성이 꺠졌다.
✅하나의 작업을 수행시키고 예외 발생 시켜보기
// 댓글 삭제
public int remove(Integer cno, Integer bno, String commenter) throws Exception {
int rowCnt = boardDao.updateCommentCnt(bno,-1); //게시판 댓글 갯수도 -1 하나 감소 처리
throw new Exception("Eception test");
commentDao.delete(cno, commenter); // 댓글을 삭제한다
}
문제를 발견하고 중간에 예외가 발생시켜보았다 . 댓글 갯수를 감소하는 작업은 처리가 되었으나 예외가 발생하여 프로그램이 종료되어 댓글을 삭제하는 작업은 처리되지않았다.
결과 : 게시판 테이블에 comment_cnt 즉 댓글 갯수는 -1 처리가 되었다
결과 : 하지만 댓글 테이블에는 해당 게시물의 댓글이 삭제가 되지 않았다.
📝해결 과정
구글링을 하면서 해당 작업을 트랜젝션으로 처리해주면 된다는 알게되었다 .
✅트랜젝션 bean 등록하기 & 라이브러리 등록
- @트랜젝션 어노테이션을 사용하기 위해서 bean 으로 등록해주었다.
✅ 해당 메서드에 @Transactional 어노테이션 붙여주기
@Override
@Transactional(rollbackFor = Exception.class)
public int remove(Integer cno, Integer bno, String commenter) throws Exception {
int rowCnt = boardDao.updateCommentCnt(bno, -1);
System.out.println("updateCommentCnt - rowCnt = " + rowCnt);
rowCnt = commentDao.delete(cno, commenter);
System.out.println("rowCnt = " + rowCnt);
return rowCnt;
}
✅테스트 해보기
@Test
public void remove() throws Exception {
boardDao.deleteAll();
BoardDto boardDto = new BoardDto("hello", "hello", "asdf");
assertTrue(boardDao.insert(boardDto) == 1);
Integer bno = boardDao.selectAll().get(0).getBno();
System.out.println("bno = " + bno);
commentDao.deleteAll(bno);
CommentDto commentDto = new CommentDto(bno,0,"hi","qwer");
assertTrue(boardDao.select(bno).getComment_cnt() == 0);
assertTrue(commentService.write(commentDto)==1);
assertTrue(boardDao.select(bno).getComment_cnt() == 1);
Integer cno = commentDao.selectAll(bno).get(0).getCno();
int rowCnt = commentService.remove(cno,bno, commentDto.getCommenter());
assertTrue(rowCnt==1);
}
✅ DB 조회
-게시판 테이블의 comment_cnt 값이 0으로 변경되고 , 댓글 테이블의 댓글은 삭제가 되었다.
✅롤백이 잘되는지 예외 발생시켜보기
@Override
@Transactional(rollbackFor = Exception.class)
public int remove(Integer cno, Integer bno, String commenter) throws Exception {
int rowCnt = boardDao.updateCommentCnt(bno, -1);
System.out.println("updateCommentCnt - rowCnt = " + rowCnt);
throw new Exception("test"); 테스트 예외 발생시키기
// rowCnt = commentDao.delete(cno, commenter);
// System.out.println("rowCnt = " + rowCnt);
// return rowCnt;
}
✅DB 확인
댓글 갯수를 삭제하고 예외가 터졌음에도 불구하고 comment_cnt 가 0이 아닌 1로 처음 상태로 rollback 되있는걸 확인할수 있다.
'토이 프로젝트 > 게시판 만들기 에러' 카테고리의 다른 글
[토이프로젝트/게시판] RedirectAttributes로 데이터 전달하기 (1) | 2024.06.11 |
---|---|
[토이프로젝트/게시판] 게시판 작성 400 에러 (0) | 2024.06.07 |
[토이프로젝트/게시판] Mybatis 연동시 'sqlSessionFactory'에러 (1) | 2024.03.22 |