[Spring] 좋아요 기능

Table 모델링

  • 현재 로직에서 필요한 데이터만 모델링 해본다면,
  • Table User
  • userId : int / not Null / primary / auto_increase
  • userName : VARCHAR / not Null
  • Table Board
  • boardId : int / not Null / primary /auto_increase
  • Title : VARCHAR / not Null
  • content : VARCHAR / not Null
  • writer : int / not Null / foreign key reference userTable
  • boardLikeCnt : int / default 0
  • Table boardLike
  • boardLikeId : int / not Null / primary / auto_increase
  • userId : int / not Null / foreign key reference userTable
  • boardId : int / not Null / foreign key reference boardTable

DAO, Mapper 작성

  • Mapper

<mapper namespace="mapper.boardLikeMapper">
        <!-- boardLike -->

        <insert id="createBoardLike">
            INSERT INTO tbl_board_like (board_id, user_id)
            VALUES (#{boardId}, #{userId})
        </insert>

        <delete id="deleteBoardLike">
            DELETE FROM tbl_board_like
            WHERE board_id = #{boardId} AND user_id = #{userId}
        </delete>

        <select id="updateBoardLike">
            UPDATE tbl_board
            SET
            board_likecnt = (SELECT COUNT(*)
            FROM tbl_board_like
            WHERE board_id = #{boardId})
            WHERE board_id = #{boardId}
        </select>

        <select id="getBoardLike" resultType="int">
            SELECT COUNT(board_like_id) FROM tbl_board_like WHERE board_id = #{boardId} AND user_id = #{userId}
        </select>

</mapper>


  • DAOImpl

    @Override
    public int getBoardLike(BoardLikeVO vo) throws Exception {
        return session.selectOne(boardLike+".getBoardLike",vo);
    }

    @Override
    public void insertBoardLike(BoardLikeVO vo) throws Exception {
        session.insert(boardLike+".createBoardLike",vo);
    }

    @Override
    public void deleteBoardLike(BoardLikeVO vo) throws Exception {
        session.delete(boardLike+".deleteBoardLike",vo);
    }

    @Override
    public void updateBoardLike(int boardId) throws Exception {
        session.update(boardLike+".updateBoardLike",boardId);
    }

Service

  • BoardServiceImpl
 
 
    @Override
    public void insertBoardLike(BoardLikeVO vo) throws Exception {
        dao.insertBoardLike(vo);
        dao.updateBoardLike(vo.getBoardId());
    }

    @Override
    public void deleteBoardLike(BoardLikeVO vo) throws Exception {
        dao.deleteBoardLike(vo);
        dao.updateBoardLike(vo.getBoardId());
    }
    
    @Override
    public  int getBoardLike(BoardLikeVO vo) throws Exception {
            return dao.getBoardLike(vo);
    }
 

Controller

  • BoardController

    @RequestMapping(value = "/read", method = RequestMethod.GET)
    public void read(@RequestParam("boardId") int boardId, Model model,
                     @ModelAttribute("cri") SearchCriteria cri,
                     @ModelAttribute("category") String category,
                     HttpServletRequest httpRequest) throws Exception {

        service.increaseViewcnt(boardId, category);

        model.addAttribute(service.readBoard(boardId, category));

        int userid = ((UserVO) httpRequest.getSession().getAttribute("login")).getUserId();

        BoardLikeVO vo = new BoardLikeVO();
        vo.setBoardId(boardId);
        vo.setUserId(userid);

        int boardlike = service.getBoardLike(vo);
        System.out.println(boardlike);

        model.addAttribute("heart",boardlike);
    }

  @ResponseBody
    @RequestMapping(value = "/heart", method = RequestMethod.POST, produces = "application/json")
    public int heart(HttpServletRequest httpRequest) throws Exception {

        int heart = Integer.parseInt(httpRequest.getParameter("heart"));
        int boardId = Integer.parseInt(httpRequest.getParameter("boardId"));
        int userid = ((UserVO) httpRequest.getSession().getAttribute("login")).getUserId();

        BoardLikeVO boardLikeVO = new BoardLikeVO();

        boardLikeVO.setBoardId(boardId);
        boardLikeVO.setUserId(userid);

        System.out.println(heart);

        if(heart >= 1) {
            service.deleteBoardLike(boardLikeVO);
            heart=0;
        } else {
            service.insertBoardLike(boardLikeVO);
            heart=1;
        }

        return heart;

    }

JSP


   <div style="text-align: right;">
       <a class="btn btn-outline-dark heart">
           <img id="heart" src="">
       </a>
   </div>


<script>
    $(document).ready(function () {

        var heartval = ${heart};

        if(heartval>0) {
            console.log(heartval);
            $("#heart").prop("src", "/resources/images/like2.png");
            $(".heart").prop('name',heartval)
        }
        else {
            console.log(heartval);
            $("#heart").prop("src", "/resources/images/like1.png");
            $(".heart").prop('name',heartval)
        }

        $(".heart").on("click", function () {

            var that = $(".heart");

            var sendData = {'boardId' : '${boardVO.boardId}','heart' : that.prop('name')};
            $.ajax({
                url :'/board/heart',
                type :'POST',
                data : sendData,
                success : function(data){
                    that.prop('name',data);
                    if(data==1) {
                        $('#heart').prop("src","/resources/images/like2.png");
                    }
                    else{
                        $('#heart').prop("src","/resources/images/like1.png");
                    }


                }
            });
        });
    });
</script>