댓글 기능 구현 - DAO와 Service의 작성
1. 댓글 기능 구현 순서

1) DB테이블 생성
2) Mapper XML 작성 (SQL문으로 CRUD를 작성)
3) DAO 작성 & 테스트
4) Service 작성 & 테스트
5) 컨트롤러 작성 & 테스트
6) HTML, CSS, JS, JQuery
1) DB테이블 생성
MySQL에서 DB 테이블을 생성한다.
각 항목은 다음과 같다
cno : 댓글 번호
bno : 글 번호
pcno : 대댓글 번호
comment : 댓글 내용
commenter : 댓글 남긴 사람
reg_date : 댓글 등록 날짜
up_date : 댓글 수정 날짜
CommentDto를 만든다.
package com.fastcampus.ch6.domain;
import java.util.Date;
import java.util.Objects;
public class CommentDto {
private Integer cno;
private Integer bno;
private Integer pcno;
private String comment;
private String commenter;
private Date reg_date;
private Date up_date;
public CommentDto() {}
public CommentDto(Integer bno, Integer pcno, String comment, String commenter) {
this.bno = bno;
this.pcno = pcno;
this.comment = comment;
this.commenter = commenter;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CommentDto that = (CommentDto) o;
return Objects.equals(cno, that.cno) && Objects.equals(bno, that.bno) && Objects.equals(pcno, that.pcno) && Objects.equals(comment, that.comment) && Objects.equals(commenter, that.commenter);
}
@Override
public String toString() {
return "CommentDto{" +
"cno=" + cno +
", bno=" + bno +
", pcno=" + pcno +
", comment='" + comment + '\'' +
", commenter='" + commenter + '\'' +
", reg_date=" + reg_date +
", up_date=" + up_date +
'}';
}
@Override
public int hashCode() {
return Objects.hash(cno, bno, pcno, comment, commenter);
}
public Integer getCno() {
return cno;
}
public void setCno(Integer cno) {
this.cno = cno;
}
public Integer getBno() {
return bno;
}
public void setBno(Integer bno) {
this.bno = bno;
}
public Integer getPcno() {
return pcno;
}
public void setPcno(Integer pcno) {
this.pcno = pcno;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCommenter() {
return commenter;
}
public void setCommenter(String commenter) {
this.commenter = commenter;
}
public Date getReg_date() {
return reg_date;
}
public void setReg_date(Date reg_date) {
this.reg_date = reg_date;
}
public Date getUp_date() {
return up_date;
}
public void setUp_date(Date up_date) {
this.up_date = up_date;
}
}
2) Mapper XML 작성 (SQL문으로 CRUD를 작성)
새로 commentMapper.xml 파일을 생성하고 쿼리문을 작성한다.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fastcampus.ch4.dao.CommentMapper">
<delete id="deleteAll" parameterType="int">
DELETE FROM comment
WHERE bno = #{bno}
</delete>
<select id="count" parameterType="int" resultType="int">
SELECT count(*) FROM comment
WHERE bno = #{bno}
</select>
<delete id="delete" parameterType="map">
DELETE FROM comment WHERE cno = #{cno} AND commenter = #{commenter}
</delete>
<insert id="insert" parameterType="CommentDto">
INSERT INTO comment
(bno, pcno, comment, commenter, reg_date, up_date)
VALUES
(#{bno}, #{pcno}, #{comment}, #{commenter}, now(), now())
</insert>
<select id="selectAll" parameterType="int" resultType="CommentDto">
SELECT cno, bno, pcno, comment, commenter, reg_date, up_date
FROM comment
WHERE bno = #{bno}
ORDER BY reg_date ASC, cno ASC
</select>
<select id="select" parameterType="int" resultType="CommentDto">
SELECT cno, bno, pcno, comment, commenter, reg_date, up_date
FROM comment
WHERE cno = #{cno}
</select>
<update id="update" parameterType="CommentDto">
UPDATE comment
SET comment = #{comment}
, up_date = now()
WHERE cno = #{cno} and commenter = #{commenter}
</update>
</mapper>
( src/resources 경로의 mybatis-config.xml 파일에 CommentDto에 대한 alias를 추가해줘야 parameterType에서 CommentDto를 간편하게 사용할 수 있다)
3) DAO 작성 & 테스트
package com.fastcampus.ch4.dao;
import com.fastcampus.ch4.domain.BoardDto;
import com.fastcampus.ch4.domain.SearchCondition;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class BoardDaoImpl implements BoardDao {
@Autowired
private SqlSession session;
private static String namespace = "com.fastcampus.ch4.dao.BoardMapper.";
@Override
public int count() throws Exception {
return session.selectOne(namespace+"count");
} // T selectOne(String statement)
@Override
public int deleteAll() {
return session.delete(namespace+"deleteAll");
} // int delete(String statement)
@Override
public int delete(Integer bno, String writer) throws Exception {
Map map = new HashMap();
map.put("bno", bno);
map.put("writer", writer);
return session.delete(namespace+"delete", map);
} // int delete(String statement, Object parameter)
@Override
public int insert(BoardDto dto) throws Exception {
return session.insert(namespace+"insert", dto);
} // int insert(String statement, Object parameter)
@Override
public List<BoardDto> selectAll() throws Exception {
return session.selectList(namespace+"selectAll");
} // List<E> selectList(String statement)
@Override
public BoardDto select(Integer bno) throws Exception {
return session.selectOne(namespace + "select", bno);
} // T selectOne(String statement, Object parameter)
@Override
public List<BoardDto> selectPage(Map map) throws Exception {
return session.selectList(namespace+"selectPage", map);
} // List<E> selectList(String statement, Object parameter)
@Override
public int update(BoardDto dto) throws Exception {
return session.update(namespace+"update", dto);
} // int update(String statement, Object parameter)
@Override
public int increaseViewCnt(Integer bno) throws Exception {
return session.update(namespace+"increaseViewCnt", bno);
} // int update(String statement, Object parameter)
@Override
public int searchResultCnt(SearchCondition sc) throws Exception {
// System.out.println("sc in searchResultCnt() = " + sc);
// System.out.println("session = " + session);
return session.selectOne(namespace+"searchResultCnt", sc);
} // T selectOne(String statement, Object parameter)
@Override
public List<BoardDto> searchSelectPage(SearchCondition sc) throws Exception {
return session.selectList(namespace+"searchSelectPage", sc);
} // List<E> selectList(String statement, Object parameter)
@Override
public int updateCommentCnt(Integer bno, int cnt) throws Exception {
Map map = new HashMap();
map.put("bno", bno);
map.put("cnt", cnt);
return session.update(namespace+"updateCommentCnt", map);
}
}
기존에 작성했던 BoardDaoImple에 updateCommentCnt 메소드 하나를 추가했다
board 테이블에 댓글수를 반영해야 하기 때문이다.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class CommentDaoImpl implements CommentDao {
@Autowired
private SqlSession session;
private static String namespace = "com.fastcampus.ch4.dao.CommentMapper.";
@Override
public int deleteAll(Integer bno) throws Exception {
return session.delete(namespace+"deleteAll", bno);
}
@Override
public int count(Integer bno) throws Exception {
return session.selectOne(namespace+"count", bno);
}
@Override
public int delete(Integer cno, String commenter) throws Exception {
Map map = new HashMap();
map.put("cno", cno);
map.put("commenter", commenter);
return session.delete(namespace+"delete", map);
}
@Override
public int insert(CommentDto dto) throws Exception {
return session.insert(namespace+"insert", dto);
}
@Override
public List<CommentDto> selectAll(Integer bno) throws Exception {
return session.selectList(namespace+"selectAll", bno);
}
@Override
public CommentDto select(Integer cno) throws Exception {
return session.selectOne(namespace+"select", cno);
}
@Override
public int update(CommentDto dto) throws Exception {
return session.update(namespace+"update", dto);
}
}
CommentDao를 만들어준다.
package com.fastcampus.ch4.dao;
import com.fastcampus.ch4.domain.*;
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.test.context.*;
import org.springframework.test.context.junit4.*;
import java.util.*;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
public class CommentDaoImplTest {
@Autowired
CommentDao commentDao;
@Test
public void count() throws Exception {
commentDao.deleteAll(1);
assertTrue(commentDao.count(1)==0);
}
@Test
public void delete() throws Exception {
commentDao.deleteAll(1);
CommentDto commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==1);
}
@Test
public void insert() throws Exception {
commentDao.deleteAll(1);
CommentDto commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==1);
commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==2);
}
@Test
public void selectAll() throws Exception {
commentDao.deleteAll(1);
CommentDto commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==1);
List<CommentDto> list = commentDao.selectAll(1);
assertTrue(list.size()==1);
commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==2);
list = commentDao.selectAll(1);
assertTrue(list.size()==2);
}
@Test
public void select() throws Exception {
commentDao.deleteAll(1);
CommentDto commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==1);
List<CommentDto> list = commentDao.selectAll(1);
String comment = list.get(0).getComment();
String commenter = list.get(0).getCommenter();
assertTrue(comment.equals(commentDto.getComment()));
assertTrue(commenter.equals(commentDto.getCommenter()));
}
@Test
public void update() throws Exception {
commentDao.deleteAll(1);
CommentDto commentDto = new CommentDto(1, 0, "comment", "asdf");
assertTrue(commentDao.insert(commentDto)==1);
assertTrue(commentDao.count(1)==1);
List<CommentDto> list = commentDao.selectAll(1);
commentDto.setCno(list.get(0).getCno());
commentDto.setComment("comment2");
assertTrue(commentDao.update(commentDto)==1);
list = commentDao.selectAll(1);
String comment = list.get(0).getComment();
String commenter = list.get(0).getCommenter();
assertTrue(comment.equals(commentDto.getComment()));
assertTrue(commenter.equals(commentDto.getCommenter()));
}
}
만든 CommentDaoImpl을 테스트 하였다.
4) Service 작성 & 테스트
package com.fastcampus.ch4.service;
import com.fastcampus.ch4.dao.*;
import com.fastcampus.ch4.domain.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;
import java.util.*;
@Service
public class CommentServiceImpl implements CommentService {
// @Autowired
BoardDao boardDao;
// @Autowired
CommentDao commentDao;
@Autowired
public CommentServiceImpl(CommentDao commentDao, BoardDao boardDao) {
this.commentDao = commentDao;
this.boardDao = boardDao;
} // 인스턴스 주입보다 생성자 주입을 권장함(컴파일 단계에서 오류를 알 수 있으므로 실수가 적어짐)
@Override
public int getCount(Integer bno) throws Exception {
return commentDao.count(bno);
}
@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;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int write(CommentDto commentDto) throws Exception {
boardDao.updateCommentCnt(commentDto.getBno(), 1);
// throw new Exception("test");
return commentDao.insert(commentDto);
}
@Override
public List<CommentDto> getList(Integer bno) throws Exception {
// throw new Exception("test");
return commentDao.selectAll(bno);
}
@Override
public CommentDto read(Integer cno) throws Exception {
return commentDao.select(cno);
}
@Override
public int modify(CommentDto commentDto) throws Exception {
return commentDao.update(commentDto);
}
}
Service도 만들어주었다.
이번에는 생성자를 이용하여 BoardDao와 CommentDao를 주입받았다.
인스턴스 주입을 하면, 실수를 했을 때 컴파일 단계에서 오류를 찾아내기 힘들어지기 때문에
컴파일 단계에서 오류를 잡을 수 있는 생성자로 객체를 주입받는 것이 좋다.
package com.fastcampus.ch4.service;
import com.fastcampus.ch4.dao.*;
import com.fastcampus.ch4.domain.*;
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.test.context.*;
import org.springframework.test.context.junit4.*;
import java.util.*;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
public class CommentServiceImplTest {
@Autowired
CommentService commentService;
@Autowired
CommentDao commentDao;
@Autowired
BoardDao boardDao;
@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();
// 일부러 예외를 발생시키고 Tx가 취소되는지 확인해야.
int rowCnt = commentService.remove(cno, bno, commentDto.getCommenter());
assertTrue(rowCnt==1);
assertTrue(boardDao.select(bno).getComment_cnt() == 0);
}
@Test
public void write() 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);
Integer cno = commentDao.selectAll(bno).get(0).getCno();
assertTrue(boardDao.select(bno).getComment_cnt() == 1);
}
}
Service 를 테스트 했다.
5) 컨트롤러 작성 & 테스트
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<h2>commentTest</h2>
comment : <input type="text" name="comment"><br>
<button id="sendBtn" type="button">등록</button>
<button id="modBtn" type="button">수정</button>
<div id="commentList"></div>
<script>
let bno = 1217;
let showList = function(bno) {
$.ajax({
type:'GET', // 요청 메서드
url: '/ch4/comments?bno='+bno, // 요청 URI
success : function(result){
$('#commentList').html(toHtml(result)); // 서버로부터 응답이 도착하면 호출될 함수
},
error : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
}); // $.ajax()
}
$(document).ready(function(){
showList(bno);
$("#modBtn").click(function(){
let cno = $(this).attr("data-cno");
let comment = $("input[name=comment]").val();
if(comment.trim()=='') {
alert("댓글을 입력해주세요.")
$("input[name=comment]").focus()
return;
}
$.ajax({
type:'PATCH', // 요청 메서드
url: '/ch4/comments/'+cno, // 요청 URI // /ch4/comments/70 POST
headers : { "content-type": "application/json"}, // 요청 헤더
data : JSON.stringify({cno:cno, comment:comment}), // 서버로 전송할 데이터. stringify()로 직렬화 필요.
success : function(result){
alert(result);
showList(bno);
},
error : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
}); // $.ajax()
});
$("#sendBtn").click(function(){
let comment = $("input[name=comment]").val();
if(comment.trim()=='') {
alert("댓글을 입력해주세요.")
$("input[name=comment]").focus()
return;
}
$.ajax({
type:'POST', // 요청 메서드
url: '/ch4/comments?bno='+bno, // 요청 URI // /ch4/comments?bno=1217 POST
headers : { "content-type": "application/json"}, // 요청 헤더
data : JSON.stringify({bno:bno, comment:comment}), // 서버로 전송할 데이터. stringify()로 직렬화 필요.
success : function(result){
alert(result);
showList(bno);
},
error : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
}); // $.ajax()
});
$("#commentList").on("click", ".modBtn", function() {
let cno = $(this).parent().attr("data-cno");
let comment = $("span.comment", $(this).parent()).text();
// 1. comment의 내용을 input에 뿌려주기
$("input[name=comment]").val(comment);
// 2. cno전달하기
$("#modBtn").attr("data-cno", cno);
});
// $(".delBtn").click(function() {
$("#commentList").on("click", ".delBtn", function(){
let cno = $(this).parent().attr("data-cno");
let bno = $(this).parent().attr("data-bno");
$.ajax({
type:'DELETE', // 요청 메서드
url: '/ch4/comments/'+cno+'?bno='+bno, // 요청 URI
success : function(result){
alert(result)
showList(bno);
},
error : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
}); // $.ajax()
});
});
let toHtml = function (comments) {
let tmp = "<ul>";
comments.forEach(function(comment) {
tmp += '<li data-cno='+ comment.cno
tmp += ' data-pcno=' + comment.pcno
tmp += ' data-bno=' + comment.bno + '>'
tmp += ' commenter=<span class="commenter">' + comment.commenter + '</span>'
tmp += ' comment=<span class="comment">' + comment.comment + '</span>'
tmp += ' up_date='+comment.up_date
tmp += '<button class="modBtn">수정</button>'
tmp += '<button class="delBtn">삭제</button>'
tmp += '</li>'
})
return tmp + "</ul>";
}
</script>
</body>
</html>
view로 사용할 test.jsp를 만들었다.
package com.fastcampus.ch4.controller;
import com.fastcampus.ch4.dao.CommentDao;
import com.fastcampus.ch4.domain.CommentDto;
import com.fastcampus.ch4.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
//@Controller
//@ResponseBody
@RestController
public class CommentController {
@Autowired
CommentService service;
// {
// "pcno" : 0,
// "comment" : "hello",
// "commenter" : "asdf"
// }
// 댓글을 수정하는 메소드
// @ResponseBody
@PatchMapping("/comments/{cno}") // /ch4/comments/42 PATCH
public ResponseEntity<String> modify(@PathVariable Integer cno, @RequestBody CommentDto dto, HttpSession session) {
// String commenter = (String)session.getAttribute("id");
String commenter = "asdf";
dto.setCommenter(commenter);
dto.setCno(cno);
System.out.println("dto = " + dto);
try {
if(service.modify(dto)!=1)
throw new Exception("Modify failed.");
return new ResponseEntity<>("MOD_OK", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>("MOD_ERR", HttpStatus.BAD_REQUEST);
}
}
// {
// "pcno" : 0,
// "comment" : "hi"
// }
// 댓글을 등록하는 메소드
// @ResponseBody
@PostMapping("/comments") // /ch4/comments?bno=1217 POST
public ResponseEntity<String> write(@RequestBody CommentDto dto, Integer bno, HttpSession session) {
// String commenter = (String)session.getAttribute("id");
String commenter = "asdf";
dto.setCommenter(commenter);
dto.setBno(bno);
System.out.println("dto = " + dto);
try {
if(service.write(dto)!=1)
throw new Exception("Write failed.");
return new ResponseEntity<>("WRT_OK", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>("WRT_ERR", HttpStatus.BAD_REQUEST);
}
}
// 지정한 댓글을 삭제하는 메소드
@DeleteMapping("/comments/{cno}") // comments/1?bno=1195 <-- 삭제할 댓글 번호
// @ResponseBody
public ResponseEntity<String> remove(@PathVariable Integer cno, Integer bno, HttpSession session) {
// String commenter = (String)session.getAttribute("id");
String commenter = "asdf";
try {
int rowCnt = service.remove(cno, bno, commenter);
if(rowCnt!=1)
throw new Exception("Delete failed");
return new ResponseEntity<>("DEL_OK", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>("DEL_ERR", HttpStatus.BAD_REQUEST);
}
}
// 지정한 게시물의 모든 댓글을 가져오는 메소드
@GetMapping("/comments") // /comments?bno=1000 GET
// @ResponseBody
public ResponseEntity<List<CommentDto>> list(Integer bno) {
List<CommentDto> list = null;
try {
list = service.getList(bno);
// System.out.println("list = " + list);
return new ResponseEntity<List<CommentDto>>(list, HttpStatus.OK); // 200
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<List<CommentDto>>(HttpStatus.BAD_REQUEST); // 400
}
}
}
컨트롤러를 만들었다.
출처 : 스프링의 정석 : 남궁성과 끝까지 간다
'Spring & SpringBoot > Spring' 카테고리의 다른 글
@ModelAttribute와 @RequestBody의 차이점 (0) | 2022.12.28 |
---|---|
220516 Spring - Chapter 5. Spring MVC로 웹사이트 만들어보기 (0) | 2022.05.17 |
220512 Spring - Chapter 4. MyBatis로 게시판 만들기(Part.4) (0) | 2022.05.13 |
220511 Spring - Chapter 4. MyBatis로 게시판 만들기(Part.3) (0) | 2022.05.12 |
220510 Spring - Chapter 4. MyBatis로 게시판 만들기(Part.2) (0) | 2022.05.11 |