Springboot+ElementUi实现评论、回复、点赞功能

目录
  • 1.概述
  • 2.前端代码
    • 1.html
    • 2.css
    • 3.js
    • 4.api调用后台接口
  • 3.后端代码
    • 1.数据库SQL
    • 2.实体类
    • 3.daoMapper
    • 4.daoMapper实现
    • 5.service接口
    • 6.service接口实现
    • 7.controller

1.概述

做一个项目,突然需要实现回复功能,所依记录一下此次的一个实现思路,也希望给别人分享一下,估计代码还是不够完善,有空在实现分页功能。话不多说直接看效果图。主要实现了评论,回复,点赞,取消点赞,如果是自己评论的还可以删除,删除的规则是如果该评论下还有回复,也一并删除。

我这里管理的是课程id,可以根据需要把课程id换为其他核心业务的id进行关联,也可以把表进行拆分,评论表和回复表。不过我为了方便就没有进行拆分。具体的实现思路我都写有详细步骤,看注释即可

效果图:

2.前端代码

1.html

 <div>
      <div v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
        <el-avatar class="header-img" :size="40" :src="userAvatar"></el-avatar>
        <div class="reply-info">
          <div
            tabindex="0"
            contenteditable="true"
            id="replyInput"
            spellcheck="false"
            placeholder="输入评论..."
            class="reply-input"
            @focus="showReplyBtn"
            @input="onDivInput($event)"
          ></div>
        </div>
        <div class="reply-btn-box" v-show="btnShow">
          <el-button
            class="reply-btn"
            size="medium"
            @click="sendComment"
            type="primary"
          >
            发表评论
          </el-button>
        </div>
      </div>
      <div
        v-for="(item, i) in comments"
        :key="i"
        class="author-title reply-father"
      >
        <el-avatar class="header-img" :size="40" :src="item.avatar"></el-avatar>
        <div class="author-info">
          <span class="author-name">{{ item.name }}</span>
          <span class="author-time">{{ item.time }}</span>
        </div>
        <div class="icon-btn">
          <span
            v-if="item.memberId != myId"
            @click="showReplyInput(i, j,item)"
          >
            <i class="iconfont el-icon-s-comment"></i>
            {{ item.commentNum }}
          </span>
          <span v-else>
            <i class="iconfont el-icon-s-comment" @click="noReply()"></i>
            {{ item.commentNum }}
          </span>
          <span class="xin" @click="countlikeNumber('comment', i, 0, item.id)">
            <i
              class="el-icon-star-on"
              v-if="item.likeListId.indexOf(myId) != -1"
            >
            </i>
            <i class="el-icon-star-off" v-else></i>{{ item.likeCount }}
          </span>
          <span
            class="el-icon-delete"
            v-if="item.memberId == myId"
            @click="deleteCommentById(item)"
          ></span>
        </div>
        <div class="talk-box">
          <p>
            <span class="reply">{{ item.content }}</span>
          </p>
        </div>
        <!-- 回复开始 -->
        <div class="reply-box">
          <div v-for="(reply, j) in item.reply" :key="j" class="author-title">
            <el-avatar
              class="header-img"
              :size="40"
              :src="reply.avatar"
            ></el-avatar>
            <div class="author-info">
              <span class="author-name">{{ reply.name }}</span>
              <span class="author-time">{{ reply.time }}</span>
            </div>
            <div class="icon-btn">
              <span
                @click="
                  showReplyInput(i, j, reply)
                "
                v-if="reply.memberId != myId"
              >
                <i class="iconfont el-icon-s-comment"></i>
                {{ reply.commentNum }}
              </span>
              <span v-else>
                <i class="iconfont el-icon-s-comment" @click="noReply()"></i>
                {{ reply.commentNum }}
              </span>

              <span @click="countlikeNumber('reply', i, j, reply.id)">
                <i
                  class="el-icon-star-on"
                  v-if="reply.likeListId.indexOf(myId) != -1"
                >
                </i>
                <i class="el-icon-star-off" v-else></i>{{ reply.likeCount }}
              </span>
              <span
                class="el-icon-delete"
                v-if="reply.memberId == myId"
                @click="deleteCommentById(reply)"
              ></span>
            </div>
            <div class="talk-box">
              <p>
                <b style="color: red">回复 {{ reply.fromName }}:</b>
                <span class="reply">{{ reply.content }}</span>
              </p>
            </div>
            <div class="reply-box"></div>
          </div>
        </div>
        <!-- 回复结束 -->
        <div v-show="_inputShow(i)" class="my-reply my-comment-reply">
          <el-avatar
            class="header-img"
            :size="40"
            :src="userAvatar"
          ></el-avatar>
          <div class="reply-info">
            <div
              tabindex="0"
              contenteditable="true"
              spellcheck="false"
              :placeholder="replyMessage"
              @input="onDivInput($event)"
              class="reply-input reply-comment-input"
            ></div>
          </div>
          <div class="reply-btn-box">
            <el-button
              class="reply-btn"
              size="medium"
              @click="sendCommentReply(i)"
              type="primary"
            >
              发表回复
            </el-button>
          </div>
        </div>
      </div>
    </div>

2.css

.my-reply {
    padding: 10px;
    background-color: #fafbfc;
  }
  .my-reply .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .my-reply .reply-info {
    display: inline-block;
    margin-left: 5px;
    width: 80%;
  }
  @media screen and (max-width: 1200px) {
    .my-reply .reply-info {
      width: 80%;
    }
  }
  .my-reply .reply-info .reply-input {
    min-height: 20px;
    line-height: 22px;
    padding: 10px 10px;
    color: #ccc;
    background-color: #fff;
    border-radius: 5px;
  }
  .my-reply .reply-info .reply-input:empty:before {
    content: attr(placeholder);
  }
  .my-reply .reply-info .reply-input:focus:before {
    content: none;
  }
  .my-reply .reply-info .reply-input:focus {
    padding: 8px 8px;
    border: 2px solid blue;
    box-shadow: none;
    outline: none;
  }
  .my-reply .reply-btn-box {
    height: 25px;
    display: inline-block;

  }
  .my-reply .reply-btn-box .reply-btn {
    position: relative;
    float: right;
    margin-left: 15px;
  }
  .my-comment-reply {
    margin-left: 50px;
  }
  .my-comment-reply .reply-input {
    width: flex;
  }
  .author-title:not(:last-child) {
    border-bottom: 1px solid rgba(74, 136, 199, 0.3);
  }
  .reply-father {
    padding: 10px;
  }
  .reply-father .header-img {
    display: inline-block;
    vertical-align: top;
  }
  .reply-father .author-info {
    display: inline-block;
    margin-left: 5px;
    width: 60%;
    height: 40px;
    line-height: 20px;
  }
  .reply-father .author-info span {
    display: block;
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .reply-father .author-info .author-name {
    color: #000;
    font-size: 18px;
    font-weight: bold;
  }
  .reply-father .author-info .author-time {
    font-size: 14px;
  }
  .reply-father .author-info .author-count{
    font-size: 15px; color: blue;
  }
  .reply-father .icon-btn {
    width: 30%;
    padding: 0 !important ;
    float: right;
  }
  @media screen and (max-width: 1200px) {
    .reply-father .icon-btn {
      width: 20%;
      padding: 7px;
    }
  }
  .reply-father .icon-btn span {
    cursor: pointer;
  }
  .reply-father .icon-btn .iconfont {
    margin: 0 5px;
  }
  .reply-father .talk-box {
    margin: 0 50px;
  }
  .reply-father .talk-box p {
    margin: 0;
  }
  .reply-father .talk-box .reply {
    font-size: 16px;
    color: #000;
  }
  .reply-father .reply-box {
    margin: 10px 0 0 50px;
    background-color: #efefef;
  }

3.js

<script>
import commentApi from "@/api/comment";
import courseApi from "@/api/course";
import cookie from "js-cookie";

const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身,是本身,则返回
      if (el.contains(e.target)) {
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法
        binding.value(e);
      }
    }
    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
    el.vueClickOutside = documentHandler;
    document.addEventListener("click", documentHandler);
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener("click", el.vueClickOutside);
    delete el.vueClickOutside;
  },
};

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

export default {
  created() {
        // 将用户数据从本地cookie获取到
        this.getUserInfo();
        // 获取评论数据
        this.initCommentList(this.course.id);
  },
  mounted() {},
  data() {
    return {

      course: {
        courseId: "",
      },

      btnShow: false,
      index: "0",
      replyComment: "",
      subIndex: "0",
      userName: "", // 当前用户name
      userAvatar: "", // 当前用户头像
      myId: null, // 当前用户id
      replyMessage:"",
      comments: [],
      current:{}, // 当前被点击的评论对象
    };
  },
  methods: {

    // 将cookie的用户信息提取出来
    getUserInfo() {
      let user = cookie.get("userInfo");
      if (user) {
        let userInfo = JSON.parse(user);
        this.userName = userInfo.nickname;
        this.userAvatar = userInfo.avatar;
        this.myId = userInfo.id;
      }
    },
    // 获取评论数据
    initCommentList(courseId) {
      commentApi.getCommentList(courseId).then((response) => {
        // 先将获取到的数据进行转换
        let commentList = response.data.commentList;
        for (let i = 0; i < commentList.length; i++) {
          // 先将父级评论转化likeListId为数组
          commentList[i].likeListId = commentList[i].likeListId.split(",");
          // 找到子级评论将likeListId为数组
          for (let j = 0; j < commentList[i].reply.length; j++) {
            commentList[i].reply[j].likeListId =
              commentList[i].reply[j].likeListId.split(",");
          }
        }
        this.comments = commentList;
      });
    },
    // 验证用户是否登录
    userIsLogin(){
         let user = cookie.get("userInfo");
         if(user==null){
         this.$confirm('评论操作需要先登录,是否现在跳转到登录页面?', '温馨提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
           this.$router.push({path: "/login"});
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '已经为您取消跳转到登录页面'
          });
        });
        return "no"
      }
       return "yes"
    },
    /**
     * 传递一个对象过来,将其深拷贝,不会在共用同一个引用
     * targetObj:需要拷贝的对象
     *
     */
    copyObject(targetObj,type){ 

         let comment = {...targetObj}
        // 装换为以,号分割的字符串 [因为后台采用的是String进行存储]
        comment.likeListId = comment.likeListId.join(",")
        // 删除掉该属性,不然后台接收会报错
        delete comment.reply
        return comment;

    },
    // 输入框被点击是触发
    inputFocus() {
      var replyInput = document.getElementById("replyInput");
      replyInput.style.padding = "8px 8px";
      replyInput.style.border = "2px solid blue";
      replyInput.focus();
    },
    // 显示回复按钮
    showReplyBtn() {
      this.btnShow = true;
    },
    // 提示不能给自己回复
    noReply() {
      this.$message({
        message: "对不起!暂不支持自己给自己回复",
        type: "warning",
      });
    },
    // 隐藏回复按钮
    hideReplyBtn() {
      this.btnShow = false;
      replyInput.style.padding = "10px";
      replyInput.style.border = "none";
    },
    /**
     * 显示输入框[评论和回复共用]
     * i:顶级评论下标
     * j:子级评论下标
     * current:当前被点击的评论记录
     *
     */
    showReplyInput(i, j,current ) {
      this.current=current
      if (current.fatherId === "-1") {
        this.parentId = current.id;
      } else {
        this.parentId = current.fatherId;
      }
      this.replyMessage = "回复:" + current.name;
      this.comments[this.index].inputShow = false;
      this.index = i;
      this.comments[i].inputShow = true;
      this.toName = current.name;
      this.toId = current.id;
      this.subIndex = j == "0" ? "0" : j;
    },
    /**
     * 根据id删除评论(前提是该评论是当前用户所评论的)
     */
    deleteCommentById(current) {
      let comment = this.copyObject(current)
      console.log("current=",current)
      commentApi.deleteCommentById(comment).then((response) => {
        if (response.success) {
          this.$message({
            showClose: true,
            type: "success",
            message: "删除成功",
          });
          // 重新获取获取评论数据
          this.initCommentList(this.course.id);
        }
      });
    },

    /**
     *
     * 统计点赞数量
     * type:是回复还是评论
     * i:一级评论
     * j:二级评论
     */
    countlikeNumber(type, i, j, id) {
      // 判断用户是否登录
      if( this.userIsLogin()=="no") return;

      const commentObje = type == "comment" ? this.comments[i] : this.comments[i].reply[j];
      let list = commentObje.likeListId;

      if (list.length === 0 || list.indexOf(this.myId) == -1) {
        //在已经点赞的列表中未找到userId
        commentObje.isLike = true;
        commentObje.likeCount += 1;
        commentObje.likeListId.push(this.myId);

        // 将对象复制一份并且去除掉reply属性,避免后台接收数据出现异常
        let comment = this.copyObject(commentObje)
        // 发送请求到后台修改点赞数量
        commentApi.updateLikeCount(comment).then(response=>{
        if(response.success){
         // 重新获取获取评论数据
          this.initCommentList(this.course.id);
          this.$message({
            type:"success",
            message:"点赞成功"
          })
        }
      })
        console.log("点赞+1", commentObje.like, commentObje.likeListId);
      } else {
        const index = list.indexOf(this.myId);
        commentObje.isLike = false;
        commentObje.likeCount -= 1;
        commentObje.likeListId.splice(index, 1);
        console.log("点赞-1",  commentObje.likeListId);

        let comment =  this.copyObject(commentObje) 

        // 发送请求到后台修改点赞数量
        commentApi.updateLikeCount(comment).then(response=>{
        if(response.success){
            // 重新获取获取评论数据
            this.initCommentList(this.course.id);
          this.$message({
            type:"success",
            message:"取消点赞成功"
          })
        }
      })
      }

      console.log("commentObje=",  commentObje);

    },
    // 是否显示输入框
    _inputShow(i) {
      return this.comments[i].inputShow;
    },
    // 发送评论
    sendComment() {

     if( this.userIsLogin()=="no") return;

      if (!this.replyComment) {
        this.$message({
          type: "warning",
          message: "评论不能为空",
        });
      } else {
        // 评论内容对象
        let object = {};
        let input = document.getElementById("replyInput");
        object.courseId = this.course.id;
        object.name = this.userName;
        object.content = this.replyComment;
        object.avatar = this.userAvatar;
        object.commentNum = 0;
        object.likeCount = 0;
        object.fromId="-1"
        object.memberId = this.myId;
        object.isLike = false;
        object.likeListId = "0,0";
        object.parentId = "-1";
        object.time = new Date().format("yyyy-MM-dd hh:mm:ss");
        this.replyComment = "";
        input.innerHTML = "";
        commentApi.addComment(object,this.current).then((response) => {
          if (response.success) {
            // 重新获取获取评论数据
            this.initCommentList(this.course.id);
            this.$message({
              type: "success",
              message: "评论成功",
            });
          }
        });
      }
    },
    // 发送回复
    sendCommentReply(i) {
     if( this.userIsLogin()=="no") return;
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "回复不能为空",
        });
      } else {
        // 回复内容对象
        let current = {};
        if(this.current.parentId == "-1" ){
          current.parentId = this.current.id
        }else{
          current.parentId = this.current.parentId
        }
        current.courseId = this.course.id;
        current.name = this.userName;
        current.memberId = this.myId;
        current.content = this.replyComment;
        current.avatar = this.userAvatar;
        current.commentNum = 0;
        current.likeCount = 0;
        current.isLike = false;
        current.likeListId = "0,0";
        current.fromName = this.current.name;
        current.fromId = this.current.id;
        current.time = new Date().format("yyyy-MM-dd hh:mm:ss");

        // 得到当前被点击的评论对象,修改他的回复条数
        this.current.commentNum += 1
        let parent = {...this.current}
        parent.likeListId = parent.likeListId.join(",")
        delete parent.reply  // 删除掉该属性,不然后台接收会报错[后台采用的是String进行存储]
        console.log("current=",current)
        console.log("parent=",parent)
        commentApi.addComment(current,parent).then((response) => {
          if (response.success) {
            // 重新获取获取评论数据
            this.initCommentList(this.course.id);
            this.$message({
              showClose: true,
              type: "success",
              message: "回复成功",
            });
          }
        });

        // 清空输入框内容
        this.replyComment = "";
        document.getElementsByClassName("reply-comment-input")[i].innerHTML = "";
      }
    },
    onDivInput: function (e) {
      this.replyComment = e.target.innerHTML;
    }
};
</script>
<style lang="scss">
@import "@/assets/css/comment.css";
</style>

4.api调用后台接口

import request from "@/utils/request";

export default {
  // 根据课程id获取评论信息
  getCommentList(courseId) {
    return request({
      url: `/serviceedu/edu-comment/getCommentList/${courseId}`,
      method: "get",
    });
  },

  // 添加一条评论记录
  addComment(current,parent) {
    return request({
      url: `/serviceedu/edu-comment/addComment`,
      method: "post",
      data:{current,parent}
    });
  },

  // 根据评论id删除一条记录
  deleteCommentById(current) {
    return request({
      url: `/serviceedu/edu-comment/deleteCommentById`,
      method: "delete",
      data:current
    });
  },

   // 修改评论的点赞数量
   updateLikeCount(comment) {
    return request({
      url: `/serviceedu/edu-comment/updateLikeCount`,
      method: "post",
      data:comment
    });
  },

};

3.后端代码

1.数据库SQL

/*
 Navicat Premium Data Transfer

 Source Server         : WindowsMysql
 Source Server Type    : MySQL
 Source Server Version : 50732
 Source Host           : localhost:3306
 Source Schema         : guli_edu

 Target Server Type    : MySQL
 Target Server Version : 50732
 File Encoding         : 65001

 Date: 24/01/2022 22:54:47
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for edu_comment
-- ----------------------------
DROP TABLE IF EXISTS `edu_comment`;
CREATE TABLE `edu_comment`  (
  `id` char(19) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '主键id',
  `course_id` varchar(19) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '课程id',
  `teacher_id` char(19) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '讲师id',
  `member_id` varchar(19) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户id',
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户昵称',
  `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户头像',
  `content` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '评论内容',
  `parent_id` char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '父级评论id\r\n',
  `comment_num` int(11) NULL DEFAULT NULL COMMENT '回复条数',
  `like_count` int(11) NULL DEFAULT NULL COMMENT '点赞数量',
  `is_like` tinyint(1) NULL DEFAULT 0 COMMENT '是否点赞',
  `like_list_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '点赞id列表',
  `input_show` tinyint(1) NULL DEFAULT 0 COMMENT '是否显示输入框',
  `time` datetime(0) NULL DEFAULT NULL COMMENT '评论创建时间',
  `from_id` char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '回复记录id\r\n',
  `from_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '回复人名称\r\n',
  `gmt_modified` datetime(0) NOT NULL COMMENT '更新时间',
  `gmt_create` datetime(0) NOT NULL COMMENT '创建时间',
  `is_deleted` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `idx_course_id`(`course_id`) USING BTREE,
  INDEX `idx_teacher_id`(`teacher_id`) USING BTREE,
  INDEX `idx_member_id`(`member_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '评论' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of edu_comment
-- ----------------------------
INSERT INTO `edu_comment` VALUES ('123963852741', '1482334670241763330', '', '1484454710336294913', 'compass', 'https://thirdwx.qlogo.cn/mmopen/vi_32/1JYibUaLyibKXk4VDEvDGyEUgFNAGrIHibRY4iatO3atSD1YERDS6qZbbbdibNpnsPqYF7kJxicAGtehHAAjiajrrict7g/132', 'spring如何实现AOP功能?', '-1', 4, 2, 1, ',1191616288114163713,1484112436503019522', 0, '2021-12-01 15:42:35', '-1', NULL, '2022-01-24 13:32:50', '2022-01-23 15:42:31', 0);
INSERT INTO `edu_comment` VALUES ('123963852742', '1482334670241763330', '', '1191616288114163713', '马超', 'https://guli-edu-compass.oss-cn-hangzhou.aliyuncs.com/avatar/2022-01-16/g.png', 'Joinpoint(连接点): 在Sping程序中允许你使用通知或增强的地方,这种地方比较多,可以是方法前后,也可以是抛出异常的时,这里只提到了方法连接点,这是因为Spring只支持方法类型的连接点。再通俗一点就是哪些方法可以被增强(使用通知),这些方法称为连接点。', '123963852741', 1, 2, 1, ',1191616288114163713,1484112436503019522', 0, '2022-01-01 15:42:35', '123963852741', 'compass', '2022-01-24 13:32:50', '2022-01-23 15:42:31', 0);
INSERT INTO `edu_comment` VALUES ('123963852743', '1482334670241763330', '', '1484112436503019522', '卡夫卡', 'https://guli-edu-compass.oss-cn-hangzhou.aliyuncs.com/avatar/2022-01-16/b80d2ab57bc0401db0aee83746e94b1d-file.png', 'Pointcut(切入点): 连接点是Spinrg程序中允许你使用通知或增强的地方,但是不是所有允许使用通知或增强的地方的地方都需要通知(增强)的,只有那些被我们使用了通知或者增强的地方才能称之为切入点。再通俗一点就是类中实际被增加(使用了通知)的方法称为切入点。', '123963852741', 1, 2, 1, '0,1191616288114163713,1484112436503019522', 0, '2020-01-01 15:42:35', '123963852741', 'compass', '2022-01-24 10:36:58', '2022-01-23 15:42:31', 0);
INSERT INTO `edu_comment` VALUES ('1485288657161056257', '1482334670241763330', '', '1484454710336294913', 'compass', 'https://thirdwx.qlogo.cn/mmopen/vi_32/1JYibUaLyibKXk4VDEvDGyEUgFNAGrIHibRY4iatO3atSD1YERDS6qZbbbdibNpnsPqYF7kJxicAGtehHAAjiajrrict7g/132', '前置通知(before):在执行业务代码前做些操作,比如获取连接对象', '-1', 1, 2, 1, ',1191616288114163713,1484112436503019522', 0, '2022-01-23 16:29:45', '-1', NULL, '2022-01-24 10:36:47', '2022-01-23 16:29:46', 0);
INSERT INTO `edu_comment` VALUES ('1485348435136622593', '1482334670241763330', '', '1191616288114163713', '马超', 'https://guli-edu-compass.oss-cn-hangzhou.aliyuncs.com/avatar/2022-01-16/g.png', 'Weaving(织入):将 Aspect 和其他对象连接起来, 并创建 Adviced object 的过程', '1485288657161056257', 0, 2, 1, ',1191616288114163713,1484112436503019522', 0, '2022-01-23 20:27:18', '123963852741', 'compass', '2022-01-24 10:45:55', '2022-01-23 20:27:18', 0);
INSERT INTO `edu_comment` VALUES ('1485352669110349825', '1482334670241763330', '', '1191600824445046786', '司马懿', '\r\nhttps://img-blog.csdnimg.cn/2df9541c7fd044ff992ff234a29ca444.png?x-oss-process=image/resize,m_fixed,h_300', 'before advice, 在 join point 前被执行的 advice. 虽然 before advice 是在 join point 前被执行, 但是它并不能够阻止 join point 的执行, 除非发生了异常(即我们在 before advice 代码中, 不能人为地决定是否继续执行 join point 中的代码)', '123963852741', 0, 2, 1, ',1191616288114163713,1484112436503019522', 0, '2022-01-23 20:44:07', '123963852743', '卡夫卡', '2022-01-24 10:47:37', '2022-01-23 20:44:07', 0);
INSERT INTO `edu_comment` VALUES ('1485606518391865345', '1482334670241763330', '', '1484112436503019522', '卡夫卡', 'https://guli-edu-compass.oss-cn-hangzhou.aliyuncs.com/avatar/2022-01-16/b80d2ab57bc0401db0aee83746e94b1d-file.png', 'js中对象是引用数据类型,如果只是通过 objectB = objectA 简单的赋值,objectA 和 objectB 指向的是同一个地址', '123963852741', 0, 0, 0, '0,0', 0, '2022-01-24 13:32:49', '123963852742', '马超', '2022-01-24 13:32:50', '2022-01-24 13:32:50', 0);

SET FOREIGN_KEY_CHECKS = 1;

2.实体类

@Data
@ToString
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduComment对象", description="评论")
public class EduComment implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键id")
    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;

    @ApiModelProperty(value = "课程id")
    private String courseId;

    @ApiModelProperty(value = "讲师id")
    private String teacherId;

    @ApiModelProperty(value = "用户id")
    private String memberId;

    @ApiModelProperty(value = "用户昵称")
    private String name;

    @ApiModelProperty(value = "用户头像")
    private String avatar;

    @ApiModelProperty(value = "评论内容")
    private String content;

    @ApiModelProperty(value = "父级评论id")
    private String parentId;

    @ApiModelProperty(value = "回复条数")
    private Integer commentNum;

    @ApiModelProperty(value = "点赞数量")
    private Integer likeCount;

    @ApiModelProperty(value = "是否点赞")
    private Boolean isLike;

    @ApiModelProperty(value = "点赞id列表")
    private String likeListId;

    @ApiModelProperty(value = "是否显示输入框")
    private Boolean inputShow;

    @ApiModelProperty(value = "评论创建时间")
    private Date time;

    @ApiModelProperty(value = "被回复的记录id")
    private String fromId;

    @ApiModelProperty(value = "回复人名称")
    private String fromName;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    @ApiModelProperty(value = "更新时间")
    private Date gmtModified;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @TableLogic
    @ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
    private Boolean isDeleted;

    @ApiModelProperty(value = "回复列表")
    @TableField(exist = false)
    private List<EduComment> reply;

}

3.daoMapper

@Repository
public interface EduCommentMapper extends BaseMapper<EduComment> {

    /**
     * 根据课程id获取到所有的评论列表
     * @param courseId 课程id
     * @return
     */
    public List<EduComment> getAllCommentList(@Param("courseId") String courseId);

}

4.daoMapper实现

<?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="">

    <resultMap id="ResultCommentList" type="EduComment">
        <id property="id" column="id"/>
        <result property="courseId" column="course_id"/>
        <result property="teacherId" column="teacher_id"/>
        <result property="memberId" column="member_id"/>
        <result property="name" column="name"/>
        <result property="avatar" column="avatar"/>
        <result property="content" column="content"/>
        <result property="parentId" column="parent_id"/>
        <result property="commentNum" column="comment_num"/>
        <result property="likeCount" column="like_count"/>
        <result property="isLike" column="is_like"/>
        <result property="likeListId" column="like_list_id"/>
        <result property="inputShow" column="input_show"/>
        <result property="fromId" column="from_id"/>
        <result property="fromName" column="from_name"/>
        <result property="time" column="time"/>
        <result property="gmtModified" column="gmt_modified"/>
        <result property="gmtCreate" column="gmt_create"/>
        <result property="isDeleted" column="is_deleted"/>
        <collection property="reply" ofType="EduComment"  column="id" select="getReplyList">

        </collection>
    </resultMap>
    <select id="getAllCommentList" resultMap="ResultCommentList" parameterType="String">
        SELECT
         id, course_id, teacher_id, member_id, name, avatar, content, parent_id,
               comment_num, like_count, is_like, like_list_id, input_show, time,
               from_id, from_name, gmt_modified, gmt_create, is_deleted
        FROM
            edu_comment
        WHERE
            parent_id = '-1'
          AND course_id = #{courseId} AND is_deleted!=1;
    </select>

    <select id="getReplyList" resultMap="ResultCommentList">
        select
            id, course_id, teacher_id, member_id, name, avatar, content, parent_id,
            comment_num, like_count, is_like, like_list_id, input_show, time,
            from_id, from_name, gmt_modified, gmt_create, is_deleted
        from edu_comment
        where parent_id=#{id} AND is_deleted!=1;
    </select>

</mapper>

5.service接口

public interface EduCommentService extends IService<EduComment> {

    /**
     * 根据课程id获取到所有的评论列表
     * @param courseId 课程id
     * @return
     */
    public List<EduComment> getAllCommentList(@Param("courseId") String courseId);

    /**
     * 根据评论id删除一条记录[是本人评论的记录]
     * @param comment 评论对象中包含回复人的id也包含被回复人的id
     * @return
     */
    public  Integer deleteCommentById(EduComment comment);

    /**
     * 添加一条评论或回复记录
     * @param current 当前提交的新comment对象
     * @param  parent  当前被点击回复的对象[评论时不需要,回复需要根据他进行判断]
     * @param token 根据request对象取到token获取用户信息
     * @return
     */
    int addComment(EduComment current,EduComment parent, HttpServletRequest token);

    /**
     * 修改点赞数量
     * @param eduComment 评论对象
     * @return
     */
    public int updateLikeCount(EduComment eduComment);

}

6.service接口实现

@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {

    @Autowired
    private EduCommentMapper eduCommentMapper;

    @Autowired
    private UserCenterClient userCenterClient;

    @Override
    public List<EduComment> getAllCommentList(String courseId) {
        return eduCommentMapper.getAllCommentList(courseId);
    }

    @Override
    @Transactional
    public Integer deleteCommentById(EduComment comment) {
        int deleteCount=1;
      try {
          // 先查询该评论是不是一条顶级评论
          QueryWrapper<EduComment> isParentWrapper  = new QueryWrapper<>();
          isParentWrapper.eq("id",comment.getId());
          isParentWrapper.eq("parent_id",-1);
          Integer count = eduCommentMapper.selectCount(isParentWrapper);
          // 如果count大于0说明该评论是一条顶级评论,先删除他的子级评论
          if (count>=0){
              QueryWrapper<EduComment> wrapper  = new QueryWrapper<>();
              wrapper.eq("parent_id",comment.getId());
              eduCommentMapper.delete(wrapper);
          }
          // 最后再删除父级评论
          QueryWrapper<EduComment> wrapper  = new QueryWrapper<>();
          wrapper.eq("member_id",comment.getMemberId());
          wrapper.eq("id",comment.getId());
          eduCommentMapper.delete(wrapper);

          // 找到该记录的顶级评论让他的评论数-1
          String parentId = comment.getParentId();
          String fromId = comment.getFromId();
          if (!StringUtils.isEmpty(parentId) && parentId.equals(fromId)){
              EduComment eduComment = this.getById(parentId);
              if (eduComment!=null){
                  eduComment.setCommentNum(eduComment.getCommentNum()-1);
                  this.updateLikeCount(eduComment);
              }
          }

         // 考虑到不是顶级记录的直接子记录的情况 fromId:表示该记录回复的是那一条记录
         if (!StringUtils.isEmpty(parentId) && !parentId.equals(fromId)){
             // 更新他的直接父级
             EduComment father = this.getById(fromId);
             if (father!=null){
                 father.setCommentNum(father.getCommentNum()-1);
                 this.updateLikeCount(father);
             }
             // 更新他的跟节点评论数量
             EduComment root = this.getById(parentId);
             if (root!=null){
                 root.setCommentNum(root.getCommentNum()-1);
                 this.updateLikeCount(root);
             }
         }

      }catch (Exception e){
          e.printStackTrace();
          deleteCount = -1;
      }
        return deleteCount ;

    }

    @Override
    @Transactional
    public int addComment(EduComment current, EduComment parent ,HttpServletRequest token) {

        // mybatis-plus总是出现逻辑删除修改返回的影响条数为0的情况,所有进行异常捕捉,捕捉到异常返回-1表示失败
        try {

            if (StringUtils.isEmpty(token)){
                throw  new GuLiException(20001,"对不起!添加失败");
            }
            // 从请求头中根据token获取用户id
            String result = JwtUtils.getMemberIdByJwtToken(token);
            if (result.equals("error")){
                throw  new GuLiException(20001,"登录时长过期,请重新登录");
            }

            // 是一条顶级评论,直接进行添加操作 如果他的parentId=-1那就是顶级评论[发表评论]
            if (current!=null && !StringUtils.isEmpty(current.getParentId()) && current.getParentId().equals("-1")){
                // 如果从token中解析出来的memberId等于提交数据中MemberId就评论成功,否则失败
                if (result.equals(current.getMemberId())){
                    return  eduCommentMapper.insert(current);
                }
            }

            // 如果能直接到这里,说明是一条回复评论
            if (parent!=null && StringIsEmpty.isEmpty(parent.getId(),parent.getParentId())){

                // 修改当前被回复的记录的总回复条数+1 [前端传递过来的时候已经+1,直接按照id修改即可]
                this.updateLikeCount(parent);
                // 根据parentId查询一条记录
                EduComment root  = this.getById(parent.getParentId());
                if (root!=null && root.getParentId().equals("-1")){
                    // 根据当前被回复的记录找到顶级记录,将顶级记录也+1
                    root.setCommentNum(root.getCommentNum()+1);
                     this.updateLikeCount(root);
                }
                // 如果从token中解析出来的memberId等于提交数据中MemberId就评论成功,否则失败
                if (result.equals(current.getMemberId())){
                    return  eduCommentMapper.insert(current);
                }

            }

        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
        return -1;
    }

    @Override
    public int updateLikeCount(EduComment eduComment) {
        return  eduCommentMapper.updateById(eduComment);
    }

}

7.controller

@Api(value = "EduCommentController",description = "前台评论控制器")
@CrossOrigin
@RestController
@RequestMapping("/serviceedu/edu-comment")
public class EduCommentController {

    @Autowired
    private EduCommentService eduCommentService;

    @GetMapping("getCommentList/{courseId}")
    @ApiOperation(value = "根据课程id查询评论信息",notes = "传入课程id")
    public R getCommentList(@PathVariable String courseId){

        return R.ok().data("commentList",eduCommentService.getAllCommentList(courseId));
    }

    @DeleteMapping("deleteCommentById")
    @ApiOperation(value = "根据评论id删除一条记录",notes = "被点击的当前记录对象")
    public R deleteCommentById(@RequestBody EduComment comment){
         int updateCount = eduCommentService.deleteCommentById(comment);
        return updateCount !=-1 ?R.ok():R.error();
    }

    @PostMapping("addComment")
    @ApiOperation(value = "添加一条评论记录",notes = "json类型的评论对象")
    public R addComment(@RequestBody Map<String,EduComment> map,HttpServletRequest token){
        EduComment parent = map.get("parent");
        EduComment current = map.get("current");

        int updateCount = eduCommentService.addComment(current,parent,token);
        return updateCount!=-1?R.ok():R.error();
    }

    @PostMapping("updateLikeCount")
    @ApiOperation(value = "修改点赞数量",notes = "传递完整的EduComment对象")
    public R updateLikeCount(@RequestBody EduComment comment){

        int  updateLikeCount = eduCommentService.updateLikeCount(comment);
        return updateLikeCount>0?R.ok():R.error();
    }

}

以上就是Springboot+ElementUi实现评论、回复、点赞功能的详细内容,更多关于Springboot ElementUi的资料请关注我们其它相关文章!

(0)

相关推荐

  • SpringBoot实现物品点赞功能

    前后端分离项目–二手交易平台小程序 SpringBoot----物品收藏功能实现 SpringBoot----评论回复功能实现(数据库设计) SpringBoot----文件(图片)上传与显示(下载) 点赞 这个功能耗费了我挺多时间,简单实现很简单,就++ – .但是还是感觉这种点赞是一个高频率的请求,而且搜的时候我看都是使用redis做缓存.b站也搜到一个视频来着,也是一样的. 效果: 功能: 首先还是一个先发请求返回数据,但是先数据存到了redis中,然后使用springboot定时任务每隔

  • Springboot项目中运用vue+ElementUI+echarts前后端交互实现动态圆环图(推荐)

    目录 如何运用vue+echarts前后端交互实现动态饼图 前言 一.环境配置 1.1 安装acharts 1.2 全局引用 二.圆环图前端实现 2.1 先在vue页面添加渲染盒子 2.2 前端逻辑实现部分 2.3 展示(可按自己需求更改前端样式) 三.前后端数据交互实现 3.1 创建数据库 3.2 后台代码的编写 如何运用vue+echarts前后端交互实现动态饼图 前言 我们做项目的时候,常常需要一些统计图来展示我们的数据,作为web开发人员,会实现统计图是我们必会的技能.我将带大家来实现动

  • 非常全面的Java SpringBoot点赞功能实现

    目录 前言 解决方案 青铜版 白银版 黄金版 源码 总结 前言 最近公司在做一个NFT商城的项目,大致就是一个只买卖数字产品的平台,项目中有个需求是用户可以给商品点赞,还需要获取商品的点赞总数,类似下图 起初感觉这功能很好实现,无非就是加个点赞表嘛,后来发现事情并没有这么简单. 一开始的设计是这样的,一共有三张表:商品表.用户表.点赞表,用户点赞的时候把用户id和商品id加到点赞表中,并给对应的商品点赞数+1.看起来没什么问题,逻辑也比较简单,但是测试的时候缺发现了奇怪的bug,点赞数量有时候会

  • SpringBoot实现评论回复功能(数据库设计)

    前后端分离项目–二手交易平台小程序 SpringBoot----物品点赞功能实现 SpringBoot----物品收藏功能实现 SpringBoot----文件(图片)上传与显示(下载) 评论回复 这个是模仿b站的那种,感觉挺好看的,同时也是因为csdn搜到了一个类似的,对于第一次做有参考要好做的多. 效果图: 数据库设计 分为评论主表和子表.主表存放的是对物品的评论,而子表存放的是对该评论的回复,就是物品 1–n主表 1 – n子表. 主表: SET FOREIGN_KEY_CHECKS=0;

  • Springboot+ElementUi实现评论、回复、点赞功能

    目录 1.概述 2.前端代码 1.html 2.css 3.js 4.api调用后台接口 3.后端代码 1.数据库SQL 2.实体类 3.daoMapper 4.daoMapper实现 5.service接口 6.service接口实现 7.controller 1.概述 做一个项目,突然需要实现回复功能,所依记录一下此次的一个实现思路,也希望给别人分享一下,估计代码还是不够完善,有空在实现分页功能.话不多说直接看效果图.主要实现了评论,回复,点赞,取消点赞,如果是自己评论的还可以删除,删除的规

  • php实现评论回复删除功能

    简单的评论回复删除功能,具体内容如下 一.数据库 建立两张表,一是pinglun表:二是huifu表 效果如下: 代码如下: 1.主页面 main.php <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <h1>朋友圈</h1> <div>内容:</div>

  • JavaScript评论点赞功能的实现方法

    通过分析评论功能的逻辑关系,学会如何使用JavaScript实现评论.回复.点赞等各种功能 1.学会JavaScript处理日期和时间. 2.掌握Dom操作中的添加/删除子节点方法. 3.使用setTimeout设置定时器. 4.使用clearTimeout清除定时器以及事件代理的运用. 效果图: 1)实现删除分享内容功能 利用事件代理实现点击关闭按钮删除分享内容. 删除事件: 利用事件代理功能,在父元素节点上添加事件,以减少代码量和系统运行负荷. 事件代理的时候,使用事件对象中的srcElem

  • thinkPHP实现基于ajax的评论回复功能

    本文实例讲述了thinkPHP实现基于ajax的评论回复功能.分享给大家供大家参考,具体如下: 控制器代码: <?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ $num = M('comment')->count(); //获取评论总数 $this->assign('num',$num); $d

  • Java实现评论回复功能的完整步骤

    前言 使用递归循环开发评论回复功能,适用于大部分的简单单体应用 评论功能或许是大多数的单体应用之中会用到的功能,我们会在自己所开发的项目之中进行集成该功能 大多数时候我们会将评论功能划分成以下几种: 单一型 嵌套型 两层型 一.分类方式 1.单一型 单一型评论方式就是日常论坛之中的盖楼的方式 用户只能根据所在的文章或者问题进行单一回复,评论之间没有互动 类似于问答形式.提出问题,然后回答,一对多关系.这些回答之间没有任何联系 2.嵌套型 嵌套型评论方式会对有回复的评论进行递归,会造成后端性能不佳

  • Android 仿微博的点赞功能的实现原理(持续点赞再取消)

    产品需求,实现类似微博的持续点赞再取消功能,因为自己也偶尔刷微博,对这功能有一定的使用上的了解, 至于微博点赞的具体实现我并不知道,微博点赞在断网的情况下依然能点赞,不会提示网络异常,等有网络之后 重新刷新,实际是没有点赞的,那就针对这现象去实现吧. 避免并发,减少CPU压力,我个人会想到 HandlerThread ,不懂可以自行科普,这里只说我实现的点赞功能原理. private Timer mTimer;//定时器 private TimerTask mTask; mMap = new H

  • SpringBoot实现文件上传下载功能小结

    最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (

随机推荐