SpringBoot整合Mybatis-plus实现多级评论

2023-11-19

在本文中,我们将介绍如何使用SpringBoot整合Mybatis-plus实现多级评论功能。同时,本文还将提供数据库的设计和详细的后端代码,前端界面使用Vue2。
在这里插入图片描述

数据库设计

本文的多级评论功能将采用MySQL数据库实现,下面是数据库的设计:

用户表

用户表用于存储注册用户的信息。

属性名 数据类型 描述
id int 用户ID
username varchar(20) 用户名
password varchar(20) 密码
email varchar(30) 电子邮箱
avatar varchar(50) 头像
评论表

评论表用于存储所有的评论信息。

属性名 数据类型 描述
id int 评论ID
content text 评论内容
create_time datetime 评论创建时间
parent_id int 父级评论ID
user_id int 评论用户ID

后端实现

相关依赖

首先,我们需要在pom.xml文件中添加以下依赖:

<!-- SpringBoot依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>${spring-boot-version}</version>
</dependency>
<!-- Mybatis-plus依赖 -->
<dependency>
    <groupId>com.baomidou.mybatisplus</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus-version}</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql-version}</version>
</dependency>

其中,${spring-boot-version}${mybatis-plus-version}${mysql-version}需要根据实际情况进行替换。

配置文件

接下来,我们需要在application.yml文件中配置MySQL的信息:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
  # Mybatis-plus配置
  mybatis-plus:
    # 实体包路径
    typeAliasesPackage: cn.example.entity
    # Mybatis XML文件位置
    mapperLocations: classpath:mapper/*.xml
    # 自动填充策略
    global-config:
      db-config:
        id-type: auto
        field-strategy: not_empty

这里需要将dbname替换成实际的数据库名称。

实体类

然后,我们需要创建实体类UserComment,分别对应用户和评论。

@Data
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    private String avatar;
}

@Data
public class Comment {
    private Long id;
    private String content;
    private Date createTime;
    private Long parentId;
    private Long userId;
}
Mapper接口

接着,我们需要创建Mapper接口UserMapperCommentMapper,用于操作用户和评论的数据。

public interface UserMapper extends BaseMapper<User> {
}

public interface CommentMapper extends BaseMapper<Comment> {
    /**
     * 获取一级评论列表(即parent_id为null的评论)
     * @return 一级评论列表
     */
    List<Comment> listParentComments();

    /**
     * 获取二级评论列表(即parent_id不为null的评论)
     * @param parentId 父级评论ID
     * @return 二级评论列表
     */
    List<Comment> listChildComments(Long parentId);
}

BaseMapper是Mybatis-plus提供的通用Mapper接口,在使用时需要继承并指定实体类。

除此之外,我们还添加了两个自定义的方法listParentCommentslistChildComments,用于分别获取一级评论和二级评论的信息。

Service层和Controller层

最后,我们需要创建Service和Controller层,实现业务逻辑和接口。

首先是CommentService:

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    /**
     * 获取一级评论列表
     * @return 一级评论列表
     */
    public List<Comment> listParentComments() {
        return commentMapper.listParentComments();
    }

    /**
     * 获取二级评论列表
     * @param parentId 父级评论ID
     * @return 二级评论列表
     */
    public List<Comment> listChildComments(Long parentId) {
        return commentMapper.listChildComments(parentId);
    }

    /**
     * 添加评论
     * @param comment 评论信息
     */
    public void addComment(Comment comment) {
        commentMapper.insert(comment);
    }
}

然后是CommentController:

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    /**
     * 获取一级评论列表
     * @return 一级评论列表
     */
    @GetMapping("/parent")
    public ResultVo listParentComments() {
        List<Comment> comments = commentService.listParentComments();
        return ResultUtil.success(comments);
    }

    /**
     * 获取二级评论列表
     * @param parentId 父级评论ID
     * @return 二级评论列表
     */
    @GetMapping("/child")
    public ResultVo listChildComments(@RequestParam Long parentId) {
        List<Comment> comments = commentService.listChildComments(parentId);
        return ResultUtil.success(comments);
    }

    /**
     * 添加评论
     * @param comment 评论信息
     */
    @PostMapping("/add")
    public ResultVo addComment(@RequestBody Comment comment) {
        comment.setCreateTime(new Date());
        commentService.addComment(comment);
        return ResultUtil.success();
    }
}

这里的ResultVoResultUtil是用于封装返回结果的工具类,这里不做过多解释。

前端实现

前端界面使用Vue实现。具体实现过程这里不做过多解释,在此提供代码供参考:

<template>
  <div class="comment-box">
    <h2>评论区域</h2>
    <h3>发表评论</h3>
    <form @submit.prevent="addComment">
      <div class="form-item">
        <label>评论内容:</label>
        <textarea v-model="comment.content" required></textarea>
      </div>
      <button type="submit">提交</button>
    </form>
    <h3>一级评论</h3>
    <ul>
      <li v-for="comment in parentComments" :key="comment.id">
        <p>{{comment.content}}</p>
        <button @click="showChildComments(comment.id)">查看回复</button>
        <div v-show="showChildCommentId === comment.id">
          <h4>二级评论</h4>
          <ul>
            <li v-for="comment in childComments" :key="comment.id">
              <p>{{comment.content}}</p>
            </li>
          </ul>
        </div>
      </li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      comment: {
        content: '',
      },
      parentComments: [],
      childComments: [],
      showChildCommentId: null,
    };
  },
  methods: {
    // 获取一级评论列表
    getParentComments() {
      axios.get('/comment/parent').then(res => {
        this.parentComments = res.data.data;
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取二级评论列表
    getChildComments(parentId) {
      axios.get('/comment/child', {params: {parentId}}).then(res => {
        this.childComments = res.data.data;
      }).catch(err => {
        console.log(err);
      });
    },
    // 添加评论
    addComment() {
      axios.post('/comment/add', this.comment).then(res => {
        this.comment.content = '';
        this.getParentComments();
      }).catch(err => {
        console.log(err);
      });
    },
    // 显示二级评论
    showChildComments(parentId) {
      if(this.showChildCommentId === parentId) {
        this.showChildCommentId = null;
        this.childComments = [];
      }else {
        this.showChildCommentId = parentId;
        this.getChildComments(parentId);
      }
    }
  },
};

</script>
<style>
.comment-box {
  font-family: Arial, sans-serif;
  max-width: 800px;
  margin: auto;
}

.form-item {
  margin-top: 10px;
}

.form-item label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
}

.form-item textarea {
  width: 100%;
  height: 100px;
  border: 1px solid #ccc;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  margin-top: 10px;
}

li p {
  margin: 0;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}
</style>

总结

本文介绍了如何使用SpringBoot整合Mybatis-plus实现多级评论功能,同时提供了数据库的设计和详细的后端代码,前端界面使用的Vue2,希望本文能够对您有所帮助。如果有任何疑问或建议,请在评论区留言,感谢您的阅读!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot整合Mybatis-plus实现多级评论 的相关文章

随机推荐

  • 如何轻松实现跨境电商,华为云解决方案告诉你

    一 跨境电商 服务器宕机怎么办 各位观众老爷们好 接下来我将介绍我们的主人公 这个男孩看好了 他叫小帅 是一名公司技术主管 并且单身暗恋小美 另外一个女孩 她叫小美 是该公司的高级程序员 同时对小帅也颇有好感 作为跨境电商员工的小美 今天又
  • 【报错解决办法】bad restore file magic number (file may be corrupted) -- no data loaded

    今天在服务器上load一个Rdata的时候出现了这个报错 这还是第一次 之前load的都没问题 重装过一次R 上网一搜 发现是r的版本不对 检查之后发现确实如此 windows的R是4 1 2的版本 而linux上是3 6 于是我就重新在l
  • mongo- spring boot 操作- and or查询

    mongo spring boot 操作 and or查询 场景 select from user where address 上海 age gt 10 and name 小明 or nickName like 小明 以前查询在 mongo
  • lfs在Mandrake安装下的安装的一些体验

    首先 在第一遍安装GCC的时候 提示 cannot find lc 从网上搜索出来的都是提示需要安装一个glibc static的这么一个包 我就找阿找阿 找了半天 反正是没有能够找到一个合适的版本出来 这就让我服了 还好 我在编译GCC的
  • 改用DirectShow+Opencv解决外置单USB接口的双目摄像头调用cv::VideoCapture打不开的问题

    最近在做windows人脸识别的项目中遇到一个很纳闷的问题 采用OpenCv库的VideoCapture打不开外置单USB双目摄像头 其他的只要是一个摄像头一跟USB就可以打开 在网上找了很多资料 七七八八的最终得以解决了 在这整理下 环境
  • 用虚幻4开发搭积木的VR游戏

    2016 年 9 月 23 24 日 由 CSDN 和创新工场联合主办的 MDCC 2016 移动开发者大会 中国 Mobile Developer Conference China 将在北京 国家会议中心召开 来自iOS Android
  • 如何创建一个Windows软件

    很久以前我创造了一个Windows软件 我今天把这个方法分享给大家 我的系统 Edition Windows 11 Pro Insider Preview Version 22H2 Installed on 7 30 2022 OS bui
  • 掘金个人主页头像旋转效果

    img src https sf1 ttcdn tos pstatp com img user avatar d1d3c1b115358ea70f51edcd697b58b2 300x300 image alt 钱端挖掘机师傅的个人资料头像
  • 服务器cpu最多几核心,决定虚拟服务器所需要的CPU核心数量是一件非常复杂的事情...

    决定虚拟服务器所需要的CPU核心数量是一件非常复杂的事情 但是综合考虑下面几个因素 相信管理员能够作出最适合于自己的决定 看起来决定虚拟服务器所需要的单颗CPU核心数量是一件非常简单的事情 但事实上有很多复杂因素需要考虑 首先 在虚拟环境C
  • ES索引库的别名的使用--不停服实现索引库的重建切换

    ES 的别名不停停服切换索引 线上发布 场景 我们现在线上正在使用 ES索引库 V 没有使用ES索引库别名 两个问题 现在由于字段更新 把线上的数据重新写入了V1库 现在如何在不断服的情况下 完美的实现 从V 切换到V1 索引库 后续如果再
  • 我的世界 服务器文件ess,求助服务器ess插件报错怎么解

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 12 54 56 ERROR Could not pass event PlayerInteractEvent to Essentials v2 15 0 52 java lang NoSuch
  • 以AI学AI系列——不懂就问(一)

    1 问 如果我想实现一个小型的类似chatGpt的应用 能够理解我输入的语音 我需要怎么做 回答 Based on your latest question it seems that you are interested in train
  • [图像处理]边缘提取以及Harris角点检测

    在本周的计算机视觉与模式识别作业中 给定输入图像是两张普通A4打印纸 上面可能有手写笔记或者打印内容但是拍照时角度不正 要求输出 1 图像的边缘 2 计算 A4纸边缘的各直线方程 3 提取A4纸的4个角点 作业要求的是使用C 的CImg库
  • Android系统启动流程,从init.rc 到 launcher 加载过程分析

    Android系统启动流程 从init rc 到 launcher 启动过程分析 目录 1 zygote 启动分析 1 1 init进程的入口函数 1 2 解析init rc 1 3 app main cpp 解析zygote启动参数 1
  • 传统IO与零拷贝

    传统IO 传统的 I O 数据传输是指在计算机系统中 使用输入 输出 I O 操作进行数据传输的一种方式 这种方式通常涉及将数据从内存传输到外部设备 如磁盘 网络等 或从外部设备传输到内存 传统的 I O 数据传输通常采用阻塞式的方式 即在
  • C# 4.0的一些新特性

    vs2010正式版4月12日发布了 前几天我也下了一个 但这几天都没有时间好好试用一下 今天针对C 语言的新特性使用了一下 感觉还不错 有几个新特性和大家分享一下 希望我没有太火星 一 新关键词 dynamic 在新版本的C 中 dynam
  • 【尚硅谷】SSM框架之SSM学习笔记

    MyBatis MyBatis简介 MyBatis历史 MyBatis最初是Apache的一个开源项目iBatis 2010年6月这个项目由Apache Software Foundation迁移到了Google Code 随着开发团队转投
  • rust + ffmpeg + sdl2 视频播放器,用纯RUST实现音视频流媒体服务

    Rust是一门系统编程语言 专注于安全 尤其是并发安全 支持函数式和命令式以及泛型等编程范式的多范式语言 RTMP协议确实复杂 在做这个项目之前 看过很多帖子 看过官方文档 但总是感觉不能彻底的理解清楚 在实现过一遍此协议之后 感觉清楚了不
  • 浅谈以太坊智能合约的设计模式与升级方法

    浅谈以太坊智能合约的设计模式与升级方法 1 最佳实践 2 实用设计案例 2 1 控制器合约与数据合约 1 gt 1 2 2 控制器合约与数据合约 1 gt N 2 3 控制器合约与数据合约 N gt 1 2 4 控制器合约与数据合约 N g
  • SpringBoot整合Mybatis-plus实现多级评论

    在本文中 我们将介绍如何使用SpringBoot整合Mybatis plus实现多级评论功能 同时 本文还将提供数据库的设计和详细的后端代码 前端界面使用Vue2 数据库设计 本文的多级评论功能将采用MySQL数据库实现 下面是数据库的设计