溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot怎么整合Mybatis-plus實現(xiàn)多級評論功能

發(fā)布時間:2023-05-04 15:46:44 來源:億速云 閱讀:167 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“SpringBoot怎么整合Mybatis-plus實現(xiàn)多級評論功能”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“SpringBoot怎么整合Mybatis-plus實現(xiàn)多級評論功能”文章能幫助大家解決問題。

數(shù)據(jù)庫設(shè)計

用戶表

用戶表用于存儲注冊用戶的信息。

屬性名數(shù)據(jù)類型描述
idint用戶ID
usernamevarchar(20)用戶名
passwordvarchar(20)密碼
emailvarchar(30)電子郵箱
avatarvarchar(50)頭像

評論表

用于存儲所有的評論信息。

屬性名數(shù)據(jù)類型描述
idint評論ID
contenttext評論內(nèi)容
create_timedatetime評論創(chuàng)建時間
parent_idint父級評論ID
user_idint評論用戶ID

后端實現(xiàn)

相關(guān)依賴

首先,我們需要在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驅(qū)動 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql-version}</version>
</dependency>

其中,${spring-boot-version}、${mybatis-plus-version}${mysql-version}需要根據(jù)實際情況進行替換。

配置文件

接下來,我們需要在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替換成實際的數(shù)據(jù)庫名稱。

實體類

然后,我們需要創(chuàng)建實體類UserComment,分別對應(yīng)用戶和評論。

@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接口

接著,我們需要創(chuàng)建Mapper接口UserMapperCommentMapper,用于操作用戶和評論的數(shù)據(jù)。

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層

最后,我們需要創(chuàng)建Service和Controller層,實現(xiàn)業(yè)務(wù)邏輯和接口。

首先是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是用于封裝返回結(jié)果的工具類,這里不做過多解釋。

前端實現(xiàn)

前端界面使用Vue實現(xiàn)。具體實現(xiàn)過程這里不做過多解釋,在此提供代碼供參考:

<template>
  <div class="comment-box">
    <h3>評論區(qū)域</h3>
    <h4>發(fā)表評論</h4>
    <form @submit.prevent="addComment">
      <div class="form-item">
        <label>評論內(nèi)容:</label>
        <textarea v-model="comment.content" required></textarea>
      </div>
      <button type="submit">提交</button>
    </form>
    <h4>一級評論</h4>
    <ul>
      <li v-for="comment in parentComments" :key="comment.id">
        <p>{{comment.content}}</p>
        <button @click="showChildComments(comment.id)">查看回復(fù)</button>
        <div v-show="showChildCommentId === comment.id">
          <h5>二級評論</h5>
          <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>

關(guān)于“SpringBoot怎么整合Mybatis-plus實現(xiàn)多級評論功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI