Browse Source

게시물 별 댓글 전체 조회 및 댓글 생성

sangwonlee 3 years ago
parent
commit
d422b0635d

+ 50 - 2
realworld/src/main/java/com/dbs/realworld/controller/ArticleController.java

@@ -10,9 +10,11 @@ import javax.servlet.http.HttpSession;
 
 import com.dbs.realworld.common.Views;
 import com.dbs.realworld.dto.ArticleDTO;
+import com.dbs.realworld.dto.CommentDTO;
 import com.dbs.realworld.dto.UserDTO;
 import com.dbs.realworld.mapper.UserMapper;
 import com.dbs.realworld.service.ArticleService;
+import com.dbs.realworld.service.CommentService;
 
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
@@ -33,12 +35,14 @@ public class ArticleController {
     
     private final ArticleService articleService;
     private final UserMapper userMapper;
+    private final CommentService commentService;
 
 
     @Autowired
-    public ArticleController(ArticleService articleService, UserMapper userMapper) {
+    public ArticleController(ArticleService articleService, UserMapper userMapper, CommentService commentService) {
         this.articleService = articleService;
         this.userMapper = userMapper;
+        this.commentService = commentService;
     }
 
 
@@ -71,6 +75,51 @@ public class ArticleController {
     }
 
 
+    @PostMapping("/{articleId}/comment")
+    public ResponseEntity saveComment(HttpServletRequest request, @PathVariable("articleId") int articleId, @RequestBody CommentDTO commentDTO) {
+        // 사용자 정보 확인
+        HttpSession session = request.getSession();
+        String ssEmail = (String) session.getAttribute("ssEmail");
+        UserDTO finded = this.userMapper.selectUserByEmail(ssEmail);
+
+        if (finded == null) {
+            ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("존재하지 않는 사용자 입니다.");
+        }
+
+        // 게시글 확인
+        ArticleDTO targetArticle = articleService.findByArticleId(articleId);
+        if (targetArticle == null) {
+            ResponseEntity.status(HttpStatus.NO_CONTENT).body("존재하지 않는 게시글 입니다.");
+        }
+
+        // 댓글 삽입
+        commentDTO.setArticleId(articleId);
+        commentService.save(commentDTO);
+
+        // 리턴
+        URI uri = URI.create("/article/" + articleId + "/comment");
+        Map<String, Object> data = new HashMap<>();
+        data.put("createdCommentId", commentDTO.getId());
+        return ResponseEntity.created(uri).body(data);
+    }
+
+
+    @GetMapping("/{articleId}/comment/all")
+    public ResponseEntity getCommentsByArticleId(@PathVariable("articleId") int articleId) {
+        // 게시글 있는지 확인
+        ArticleDTO articleDTO = articleService.findByArticleId(articleId);
+        if (articleDTO == null) {
+            ResponseEntity.status(HttpStatus.NO_CONTENT).body("존재하지 않는 게시글 입니다.");
+        }
+
+        // 댓글 조회
+        List<CommentDTO> commentDTOs = commentService.findAllByArticleId(articleId);
+        Map<String, Object> data = new HashMap<>();
+        data.put("comments", commentDTOs);
+        return ResponseEntity.ok().body(data);
+    }
+
+
     @GetMapping("/{articleId}/edit")
     public String initEditForm(HttpServletRequest request, @PathVariable("articleId") int articleId, ModelMap model) {
         // 아티클 정보 조회
@@ -102,7 +151,6 @@ public class ArticleController {
      * https://stackoverflow.com/a/17376670
      * HTTP PATCH Request의 경우 바디에 아무 제약도 없다
      */
-    // @PostMapping("/{articleId}")
     @PatchMapping("/{articleId}")
     public ResponseEntity editArticle(HttpServletRequest request, @PathVariable("articleId") int articleId, @RequestBody ArticleDTO articleDTO) {
         HttpSession session = request.getSession();

+ 23 - 0
realworld/src/main/java/com/dbs/realworld/dto/CommentDTO.java

@@ -0,0 +1,23 @@
+package com.dbs.realworld.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.time.LocalDateTime;
+
+
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class CommentDTO {
+    private int id;                  // 댓글 아이디
+    private int articleId;           // 게시글 아이디
+    private String content;          // 댓글 내용
+    private LocalDateTime created;   // 댓글 생성 시간
+    private int userId;              // 댓글 작성자 아이디
+    private String email;            // 댓글 작성자 이메일
+    private String username;         // 댓글 작성자 이름
+}

+ 16 - 0
realworld/src/main/java/com/dbs/realworld/mapper/CommentMapper.java

@@ -0,0 +1,16 @@
+package com.dbs.realworld.mapper;
+
+import java.util.List;
+
+import com.dbs.realworld.dto.CommentDTO;
+
+import org.apache.ibatis.annotations.Mapper;
+import org.springframework.stereotype.Repository;
+
+@Repository
+@Mapper
+public interface CommentMapper {
+
+    void insertComment(CommentDTO dto);
+    List<CommentDTO> selectAllByArticleId(int articleId);
+}

+ 3 - 4
realworld/src/main/java/com/dbs/realworld/service/ArticleService.java

@@ -22,9 +22,8 @@ public class ArticleService {
     // uncheckedException과 error 뿐만 아니라 모든 예외에 대해 롤백하고 싶은 경우
     // @Transactional(rollbackFor = Exception.class)
     public int save(ArticleDTO articleDTO) {
-        articleMapper.insertArticle(articleDTO);
+        this.articleMapper.insertArticle(articleDTO);
         return articleDTO.getId();
-        // return articleDTO;
     }
 
     public List<ArticleDTO> findAll() {
@@ -36,10 +35,10 @@ public class ArticleService {
     }
 
     public void remove(int articleId) {
-        articleMapper.deleteByArticleId(articleId);
+        this.articleMapper.deleteByArticleId(articleId);
     }
 
     public void edit(ArticleDTO articleDTO) {
-        int result = articleMapper.updateArticle(articleDTO);
+        this.articleMapper.updateArticle(articleDTO);
     }
 }

+ 30 - 0
realworld/src/main/java/com/dbs/realworld/service/CommentService.java

@@ -0,0 +1,30 @@
+package com.dbs.realworld.service;
+
+import java.util.List;
+
+import com.dbs.realworld.dto.CommentDTO;
+import com.dbs.realworld.mapper.CommentMapper;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+public class CommentService {
+
+    private final CommentMapper commentMapper;
+
+    @Autowired
+    public CommentService(CommentMapper commentMapper) {
+        this.commentMapper = commentMapper;
+    }
+
+    public int save(CommentDTO commentDTO) {
+        commentMapper.insertComment(commentDTO);
+        return commentDTO.getId();
+    }
+
+    public List<CommentDTO> findAllByArticleId(int articleId) {
+        // List<CommentDTO> res = commentMapper.selectAllByArticleId(articleId);
+        return commentMapper.selectAllByArticleId(articleId);
+    }
+}

+ 0 - 8
realworld/src/main/resources/mybatis/mapper/user/ArticleMapper.xml

@@ -78,12 +78,4 @@
             DELETE FROM article_mst WHERE id = #{articleId}
         ]]>
     </delete>
-
-  <!-- <select id="selectMemberPassword" resultType="com.lemon.lifecenter.dto.StaffDTO">
-    <![CDATA[
-      SELECT id, password
-        FROM MEMBER
-    ]]>
-  </select> -->
-   
 </mapper>

+ 61 - 0
realworld/src/main/resources/mybatis/mapper/user/CommentMapper.xml

@@ -0,0 +1,61 @@
+<?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.dbs.realworld.mapper.CommentMapper">
+  
+   <insert id="insertComment" parameterType="CommentDTO" useGeneratedKeys="true" keyProperty="id">
+        <![CDATA[
+            INSERT 
+            INTO article_comment
+                   ( article_id,   user_id,   content,    create_datetime	)
+            VALUES ( #{articleId}, #{userId}, #{content}, #{created} )
+        ]]>
+    </insert>
+
+    
+    <select id="selectAllByArticleId" parameterType="int" resultType="CommentDTO">
+      <![CDATA[
+        SELECT
+          AC.id               AS id,
+          AC.article_id       AS articleId,
+          AC.content          AS content,
+          AC.create_datetime  AS created,
+          AC.user_id          AS userId,
+          USR.email           AS email,
+          USR.name            AS username
+        FROM article_comment AC
+        LEFT JOIN user_mst USR
+        ON AC.user_id = USR.id
+        WHERE AC.article_id = #{articleId}
+        ORDER BY AC.create_datetime DESC
+      ]]>
+    </select>
+
+    <!-- <select id="selectAllByArticleId" parameterType="int" resultType="CommentDTO">
+      <![CDATA[
+        SELECT
+          AC.id               AS id,
+          AC.article_id       AS articleId,
+          AC.content          AS content,
+          AC.create_datetime  AS created,
+          USR.id              AS userId,
+          USR.name            AS username,
+          USR.email           AS email
+        FROM article_comment AC
+        LEFT JOIN user_mst USR
+        ON AC.user_id = USR.id
+        WHERE AC.article_id = #{articleId}
+        ORDER BY AC.create_datetime DESC
+      ]]>
+    </select> -->
+
+    <!-- 댓글 맺 -->
+    <!-- <resultMap id="comment" type="com.dbs.realworld.dto.CommentDTO">
+      <id property="id"                   column="id" />
+      <result property="articleId"        column="articleId"/>
+      <result property="content"          column="content"/>
+      <result property="created"          column="created"/>
+      <result property="userId"           column="userId"/>
+      <result property="username"         column="username"/>
+      <result property="email"            column="email"/>
+    </resultMap> -->
+</mapper>