[CSBlog] MyBatis Mapper를 활용해 Comment 기능 구현하기

sorzzzzy·2022년 2월 11일
0

Spring Project

목록 보기
11/18
post-thumbnail

지난 시간에는 게시물 관련인 Post 기능을 구현했다면 이번에는 댓글 기능을 구현해 보도록 하겠다!!


🏷 댓글 기능 구현

✔️ com.codepresso.blog.vo.UserComment.java 클래스

package com.codepresso.blog.vo;
import java.util.Date;

public class UserComment {
	
	private Long id;

	private Long postId;

	private String userName;

	private String content;

	private Date regDate;
	
	public UserComment() {
	}
	
	public UserComment(Long postId, String userName, String content) {
		this.postId = postId;
		this.userName = userName;
		this.content = content;
		this.regDate = new Date();
	}

	public UserComment(Long id, String content) {
		this.id = id;
		this.content = content;
		this.regDate = new Date();
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getPostId() {
		return postId;
	}

	public void setPostId(Long postId) {
		this.postId = postId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getRegDate() {
		return regDate;
	}

	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}
}

Post 객체와 비슷하게 멤버변수와 메소드를 선언한다.


✔️ com.codepresso.blog.repository.UserCommentRepository.java 인터페이스

package com.codepresso.blog.repository;

import com.codepresso.blog.vo.UserComment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface UserCommentRepository {

    // 게시물 댓글 등록
    void saveComment(@Param("userComment") UserComment userComment);

    // 툭정 게시물 전체 댓글 조회
    List<UserComment> findOneComment(@Param("postId") Long id);
}

UserComment 는 크게 게시물에 댓글을 등록하는 기능, 특정 게시물의 전체 댓글을 조회하는 기능이 있다.
여기서도 @Param 으로 전달한 파라미터를 잘 확인하고 넘어가자.


✔️ com.codepresso.blog.service.CommentService.java 클래스

package com.codepresso.blog.service;

import com.codepresso.blog.repository.UserCommentRepository;
import com.codepresso.blog.vo.UserComment;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {

    private UserCommentRepository userCommentRepository;

    public CommentService(UserCommentRepository userCommentRepository) {
        this.userCommentRepository = userCommentRepository;
    }

    public void addUserComment(UserComment userComment) {
        userCommentRepository.saveComment(userComment);
    }

    public List<UserComment> getUserComment(Long id){
        return userCommentRepository.findOneComment(id);
    }
}

UserCommentRepository 에 대한 의존성 주입을 하고 이를 바탕으로 두가지 기능에 대한 메소드를 작성한다.


✔️ com.codepresso.blog.controller.CommentController.java 클래스

package com.codepresso.blog.controller;

import com.codepresso.blog.service.CommentService;
import com.codepresso.blog.vo.Result;
import com.codepresso.blog.vo.UserComment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CommentController {

    private CommentService commentService;

    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    @PostMapping(value = "/comment")
    public Result addUserComment(@RequestBody UserComment userComment){
        commentService.addUserComment(userComment);
        return new Result(200, "OK");
    }

    @GetMapping(value = "/comments")
    public List<UserComment> getUserComment(@RequestParam(name = "post_id") Long id){
        return commentService.getUserComment(id);
    }
}

CommentService 에 대한 의존성 주입을 한다.

각각의 메소드에 대해 HTTP Method를 위한 간소화된 어노테이션을 적용하고, Path Param을 사용하기 때문에 메소드 파라미터에 @RequestParam 어노테이션을 사용한다.
이때 name 으로 post_id 를 꼭 명시해주어야 한다.

또한 데이터 형식이 JSON 이기 때문에, @RequestBody 라는 어노테이션을 사용한다.


✔️ resources/mybatis/mapper/UserCommentMapper

<?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.codepresso.blog.repository.UserCommentRepository">
    <insert id="saveComment">
        INSERT INTO USER_COMMENT(POST_ID, USER_NAME, CONTENT)
        VALUES (#{userComment.postId}, #{userComment.userName}, #{userComment.content})
    </insert>
    <select id="findOneComment" resultType="com.codepresso.blog.vo.UserComment">
        SELECT *
        FROM USER_COMMENT WHERE POST_ID = ${postId}
    </select>
</mapper>

UserCommentRepository@Param 어노테이션으로 넘겨주었던 파라미터에 유의해 SQL문을 작성한다.


🏷 실행 결과


✔️ 게시물 등록 - POST/ localhost:8080/post


✔️ 게시물 전체 조회 - GET/ localhost:8080/posts


✔️ 특정 게시물 조회 - GET/ localhost:8080/post?id={id}


✔️ 게시물 수정 - PUT/ localhost:8080/post
변경할 내용
변경된 내용


✔️ 게시물 삭제 - DELETE/ localhost:8080/post?id={id}

➡️ H2 Database 콘솔 창 확인


✔️ 댓글 등록 - POST/ localhost:8080/comment


✔️ 특정 게시물의 댓글 조회 - GET/ localhost:8080/comment?post_id={post_id}


➡️ H2 Database 콘솔 창 확인


✔️ 웹 실행화면

profile
Backend Developer

0개의 댓글