Burninghering's Blog
article thumbnail
Published 2023. 6. 15. 22:26
댓글 기능 구현 - back 패캠 챌린지

DB부터 시작해서 DB에서 가까운 순으로 쭉 개발



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>

dao를 만들어준다.

 

@Repository 해주고

세션을 주입받는다.

 

그리고 Mapper를 보면서 메소드를 만들어준다.

package com.fastcampus.ch4.dao;

import com.fastcampus.ch4.domain.*;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.session.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.util.*;

@Repository
public class CommentDao {
    @Autowired
    private SqlSession session;
    private static String namespace = "com.fastcampus.ch4.dao.CommentMapper.";

    @Override
    public int count(Integer bno) throws Exception {
        return session.selectOne(namespace+"count", bno);
    } // T selectOne(String statement)

    @Override
    public int deleteAll(Integer bno) {
        return session.delete(namespace+"deleteAll", bno);
    } // int delete(String statement)

    @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);
    } // int delete(String statement, Object parameter)

    @Override
    public int insert(CommentDto dto) throws Exception {
        return session.insert(namespace+"insert", dto);
    } // int insert(String statement, Object parameter)

    @Override
    public List<CommentDto> selectAll(Integer bno) throws Exception {
        return session.selectList(namespace+"selectAll", bno);
    } // List<E> selectList(String statement)

    @Override
    public CommentDto select(Integer cno) throws Exception {
        return session.selectOne(namespace + "select", cno);
    } // T selectOne(String statement, Object parameter)

    @Override
    public int update(CommentDto dto) throws Exception {
        return session.update(namespace+"update", dto);
    } // int update(String statement, Object parameter)
}

 

이제 implements로 추출해준다.


domain에 CommentDto를 만들어준다.

 

오른쪽 아까 만들어준 database를 보면서 변수를 만들어준다.

package com.fastcampus.ch4.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;
    }

    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;
    }

    @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 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 int hashCode() {
        return Objects.hash(cno, bno, pcno, comment, commenter);
    }
}

 

CommentDaoImplTest.java를 만들었다.

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"}) //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()));
    }
}

에러가 떴는데,

commentMapper.xml에서 parameterType을 쓸 때 "CommnetDto"로 썼는데

앞에 패키지명을 안 적어주는.. alias를 안해주어서 그렇다.

그러려면 mybatis-config.xml에 등록해주어야한다.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="BoardDto" type="com.fastcampus.ch4.domain.BoardDto"/>
        <typeAlias alias="CommentDto" type="com.fastcampus.ch4.domain.CommentDto"/>
        <typeAlias alias="SearchCondition" type="com.fastcampus.ch4.domain.SearchCondition"/>
    </typeAliases>
</configuration>

Service를 만들고 나서, 인터페이스를 추출하는데 이름을 Impl로 고쳐준다. 

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 {

    BoardDao boardDao; //게시물에 댓글이 몇 개 달렸는지 알아야 하기 때문에

    CommentDao commentDao;

//    @Autowired
    public CommentServiceImpl(CommentDao commentDao, BoardDao boardDao) { //위 변수들에, @Autowired로 주입이 안되면 컴파일 에러가 나는데, 생성자 주입을 하면 에러가 나지 않는다 
        this.commentDao = commentDao;
        this.boardDao = boardDao;
    }

    @Override
    public int getCount(Integer bno) throws Exception {
        return commentDao.count(bno);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //카운트를 -1, 댓글 지우는 두 작업을 성공하기 위해 transactional을 걸어주었다.
    //예외가 발생하면 롤백을 걸기 위해 rollbackFor를 걸어주었다
    public int remove(Integer cno, Integer bno, String commenter) throws Exception { //댓글 삭제하기
        int rowCnt = boardDao.updateCommentCnt(bno, -1); //카운트를 -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);
    }
}

 

BoardDaoImpl.java에 추가

@Override
public int updateCommentCnt(Integer bno, int cnt) {
    Map map = new HashMap();
    map.put("cnt",cnt);
    map.put("bno",bno);
    return session.update(namespace+"updateCommentCnt",map);
}

 

boardMapper.xml에 추가

<update id="updateCommentCnt" parameterType="map">
    UPDATE board
    SET comment_cnt = comment_cnt + #{cnt}
    WHERE bno = #{bno}
</update>

 

boardDao.java에 추가

int updateCommentCnt(Integer bno, int cnt);

 

 

필드 주입보다 

생성자 주입을 권장하는 이유 :

컴파일할 때 어떠한 필드에 주입을 하지 않을 것을 알아챌 수 있다.

@Service
public class CommentServiceImpl implements CommentService {

    BoardDao boardDao; //게시물에 댓글이 몇 개 달렸는지 알아야 하기 때문에

    CommentDao commentDao;

//    @Autowired
    public CommentServiceImpl(CommentDao commentDao, BoardDao boardDao) { 
    //위 변수들에, @Autowired로 주입이 안되면 컴파일 에러가 나는데, 생성자 주입을 하면 에러가 나지 않는다
        this.commentDao = commentDao;
        this.boardDao = boardDao;
    }

CommentServiceImplTest

 

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);
    }
}

Controller 작성

@Controller
public class CommentController {
    
    @Autowired
    CommentService service;
    
    @GetMapping("comments") //comments?bno=1080 GET
    public List<CommentDto> list(Integer bno){
        List<CommentDto> list = service.getList(bno);
    }
}
@Controller
public class CommentController {

    @Autowired
    CommentService service;

    @GetMapping("comments") //comments?bno=1080 GET
    @ResponseBody public List<CommentDto> list(Integer bno){
        List<CommentDto> list=null;
        try {
             list = service.getList(bno);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}

//지정된 게시물의 모든 댓글을 가져오는 메서드
@GetMapping("comments") //comments?bno=1080 GET
@ResponseBody public ResponseEntity<List<CommentDto>> list(Integer bno){
    List<CommentDto> list=null;
    try {
         list = service.getList(bno);
        return new ResponseEntity<List<CommentDto>>(list, HttpStatus.OK); 
        //에러가 났을때 상태코드를 다르게 주기 위해 ResponseEntity (200)
        //list가 entity인데 상태코드를 추가한 것 뿐!
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<List<CommentDto>>(list, HttpStatus.BAD_REQUEST); //400
    }
}

//지정된 댓글을 삭제하는 메서드
public ResponseEntity<String> remove(Integer cno,Integer bno,HttpSession session){
    String commenter = (String)session.getAttribute("id");
    int rowCont = service.remove(cno,bno,commenter);
}
    //지정된 댓글을 삭제하는 메서드
    @DeleteMapping("/comments/{cno}") //comments/1?bno=1085 <--삭제할 댓글 번호
    @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);
        }
    }


    //댓글을 등록하는 메서드
    @ResponseBody
    @PostMapping("/comments") // /ch4/comments?bno=1085 POST
    public ResponseEntity<String> write(CommentDto dto, Integer bno, HttpSession session) {
//        String commenter = (String)session.getAttribute("id");
        String commenter = "asdf";
    }
    @ResponseBody
    @PostMapping("/comments") // /ch4/comments?bno=1085 POST
    public ResponseEntity<String> write(@RequestBody CommentDto dto, Integer bno, HttpSession session) { //json으로 온 것을 자바 객체로 변환하는 @RequestBody
//        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<String>("WRT_ERR",HttpStatus.BAD_REQUEST);
        }
    }


    @PatchMapping("/comments/{cno}")
    @ResponseBody
    public ResponseEntity<String> modify(@PathVariable Integer cno, @RequestBody CommentDto dto) {
//        String commenter = (String)session.getAttribute("id");
        dto.setCno(cno);
        System.out.println("dto = " + dto);

        try {
            if(service.modify(dto)!=1)
                throw new Exception("Write failed.");
            return new ResponseEntity<>("MOD_OK", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<String>("MOD_ERR", HttpStatus.BAD_REQUEST);
        }
    }


@ResponseBody - 메소드에 붙은 것들을 다 지우고,

클래스 위에 @Controller와 합쳐서

@RestController라고 해준다

package com.fastcampus.ch4.controller;

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;

@RestController
public class CommentController {

    @Autowired
    CommentService service;

    @PatchMapping("/comments/{cno}")
    public ResponseEntity<String> modify(@PathVariable Integer cno, @RequestBody CommentDto dto) {
//        String commenter = (String)session.getAttribute("id");
        dto.setCno(cno);
        System.out.println("dto = " + dto);

        try {
            if(service.modify(dto)!=1)
                throw new Exception("Write failed.");
            return new ResponseEntity<>("MOD_OK", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<String>("MOD_ERR", HttpStatus.BAD_REQUEST);
        }
    }

    //    {
//        "pcno":0,
//            "comment":"hi"
//    }
    @PostMapping("/comments")
    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<String>("WRT_ERR", HttpStatus.BAD_REQUEST);
        }
    }

    //지정된 댓글을 삭제하는 메서드
    @DeleteMapping("/comments/{cno}") //comments/1?bno=1085 <--삭제할 댓글 번호
    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=1080 GET
    @ResponseBody public ResponseEntity<List<CommentDto>> list(Integer bno){
        List<CommentDto> list=null;
        try {
            list = service.getList(bno);
            return new ResponseEntity<List<CommentDto>>(list, HttpStatus.OK);
            //에러가 났을때 상태코드를 다르게 주기 위해 ResponseEntity (200)
            //list가 entity인데 상태코드를 추가한 것 뿐!
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<List<CommentDto>>(list, HttpStatus.BAD_REQUEST); //400
        }
    }


}

'패캠 챌린지' 카테고리의 다른 글

답글 기능 구현  (0) 2023.06.19
댓글 기능 구현 - front  (1) 2023.06.16
REST API와 Ajax  (1) 2023.06.14
게시판 검색 기능 만들기  (0) 2023.06.12
게시판 CRUD 기능 구현_읽기, 삭제  (0) 2023.06.05
profile

Burninghering's Blog

@개발자 김혜린

안녕하세요! 반갑습니다.