MongoDB实战演练

简介: 本项目基于Spring Boot与MongoDB实现文章评论系统,涵盖评论增删改查、按文章ID查询、分页查询及点赞功能。采用SpringDataMongoDB简化数据库操作,通过MongoTemplate优化点赞逻辑,提升性能。

5.1 需求分析
某头条的文章评论业务如下:
image.png
需要实现以下功能:
1)基本增删改查API
2)根据文章id查询评论
3)评论点赞
数据库:articledb
image.png
5.3 技术选型
5.3.1 mongodb-driver(了解)
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们通过一个入门的案例来了解mongodb-driver的基本使用。
5.3.2 SpringDataMongoDB
SpringData家族成员之一,用于操作MongoDB的持久层框架,封装了底层的mongodb-driver。
官网主页: https://projects.spring.io/spring-data-mongodb/
5.4 文章微服务模块搭建
(1)搭建项目工程article,pom.xml引入依赖:
image.png
(2)创建application.yml
image.png
(3)创建启动类cn.itcast.article.ArticleApplication
image.png
(4)启动项目,看是否能正常启动,控制台没有错误。
5.5 文章评论实体类的编写
创建实体类 创建包cn.itcast.article,包下建包po用于存放实体类,创建实体类
cn.itcast.article.po.Comment
image.png
image.png
image.png
说明:
索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过Mongo的命令来添加,也可以在Java的实体类中通过注解添加。
1)单字段索引注解@Indexed
org.springframework.data.mongodb.core.index.Indexed.class
声明该字段需要索引,建索引可以大大的提高查询效率。
Mongo命令参考:
db.comment.createIndex({"userid":1})
2)复合索引注解@CompoundIndex
org.springframework.data.mongodb.core.index.CompoundIndex.class
复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
Mongo命令参考:
db.comment.createIndex({"userid":1,"nickname":-1})
5.6 文章评论的基本增删改查**
(1)创建数据访问接口 cn.itcast.article包下创建dao包,包下创建接口 cn.itcast.article.dao.CommentRepository

package cn.itcast.article.dao;

import cn.itcast.article.po.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;

//评论的持久层接口
public interface CommentRepository extends MongoRepository {

}
(2)创建业务逻辑类 cn.itcast.article包下创建service包,包下创建类 cn.itcast.article.service.CommentService

package cn.itcast.article.service;

import cn.itcast.article.dao.CommentRepository;
import cn.itcast.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

//评论的业务层
@Service
public class CommentService {

//注入dao
@Autowired
private CommentRepository commentRepository;

/**
 * 保存一个评论
 * @param comment
 */
public void saveComment(Comment comment){
    //如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
    //设置一些默认初始值。。。
    //调用dao
    commentRepository.save(comment);
}

/**
 * 更新评论
 * @param comment
 */
public void updateComment(Comment comment){
    //调用dao
    commentRepository.save(comment);
}

/**
 * 根据id删除评论
 * @param id
 */
public void deleteCommentById(String id){
    //调用dao
    commentRepository.deleteById(id);
}

/**
 * 查询所有评论
 * @return
 */
public List<Comment> findCommentList(){
    //调用dao
    return commentRepository.findAll();
}

/**
 * 根据id查询评论
 * @param id
 * @return
 */
public Comment findCommentById(String id){
    //调用dao
    return commentRepository.findById(id).get();
}

}
(3)新建Junit测试类,测试保存和查询所有:
cn.itcast.article.service.CommentServiceTest
package cn.itcast.article.service;

import cn.itcast.article.ArticleApplication;
import cn.itcast.article.po.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.List;

//测试评论的业务层
//SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
//SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

//注入Service
@Autowired
private CommentService commentService;

/**
 * 保存一个评论
 */
@Test
public void testSaveComment(){
    Comment comment=new Comment();
    comment.setArticleid("100000");
    comment.setContent("测试添加的数据");
    comment.setCreatedatetime(LocalDateTime.now());
    comment.setUserid("1003");
    comment.setNickname("凯撒大帝");
    comment.setState("1");
    comment.setLikenum(0);
    comment.setReplynum(0);
    commentService.saveComment(comment);
}

/**
 * 查询所有数据
 */
@Test
public void testFindAll(){
    List<Comment> list = commentService.findCommentList();
    System.out.println(list);
}

/**
 * 测试根据id查询
 */
@Test
public void testFindCommentById(){
    Comment comment = commentService.findCommentById("5d6a27b81b8d374798cf0b41");
    System.out.println(comment);
}

}
结果:
image.png
5.7 根据上级ID查询文章评论的分页列表 (1)CommentRepository新增方法定义
//根据父id,查询子评论的分页列表
Page findByParentid(String parentid, Pageable pageable);<br>(2)CommentService新增方法<br>/**</p> <ul> <li>根据父id查询分页列表</li> <li>@param parentid</li> <li>@param page</li> <li>@param size</li> <li>@return<br><em>/<br>public Page<Comment> findCommentListPageByParentid(String parentid,int page ,int size){<br> return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));<br>}<br>(3)junit测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em><ul> <li>测试根据父id查询子评论的分页列表<br><em>/<br>@Test<br>public void testFindCommentListPageByParentid(){<br>Page<Comment> pageResponse = commentService.findCommentListPageByParentid(&quot;3&quot;, 1, 2);<br>System.out.println(&quot;----总记录数:&quot;+pageResponse.getTotalElements());<br>System.out.println(&quot;----当前页数据:&quot;+pageResponse.getContent());<br>}<br>(4)测试<br>使用compass快速插入一条测试数据,数据的内容是对3号评论内容进行评论。<br><img src="https://ucc.alicdn.com/pic/developer-ecology/ifuxgytxbekgq_2c6b717bbab649dbbd10aae7bcf52ca1.png" alt="image.png"><br>执行测试结果:<br>----总记录数:1<br>----当前页数据:[Comment{id=&#39;33&#39;, content=&#39;你年轻,火力大&#39;, publishtime=null, userid=&#39;1003&#39;, nickname=&#39;凯撒大帝&#39;, createdatetime=null, likenum=null, replynum=null, state=&#39;null&#39;, parentid=&#39;3&#39;, articleid=&#39;100001&#39;}]<br><strong>5.8 MongoTemplate实现评论点赞</strong><br>我们看一下以下点赞的临时示例代码: CommentService 新增updateThumbup方法<br>/*</em></li> </ul> </li> <li>点赞-效率低</li> <li>@param id<br>*/<br>public void updateCommentThumbupToIncrementingOld(String id){<br> Comment comment = CommentRepository.findById(id).get();<br> comment.setLikenum(comment.getLikenum()+1);<br> CommentRepository.save(comment);<br>}<br>以上方法虽然实现起来比较简单,但是执行效率并不高,因为我只需要将点赞数加1就可以了,没必要查询出所有字段修改后再更新所有字段。我们可以使用MongoTemplate类来实现对某列的操作。<br>(1)修改CommentService<br>//注入MongoTemplate<br>@Autowired<br>private MongoTemplate mongoTemplate;</li> </ul> <p>/**</p> <ul> <li>点赞数+1</li> <li>@param id<br><em>/<br>public void updateCommentLikenum(String id){<br> //查询对象<br> Query query=Query.query(Criteria.where(&quot;_id&quot;).is(id));<br> //更新对象<br> Update update=new Update();<br> //局部更新,相当于$set<br> // update.set(key,value)<br> //递增$inc<br> // update.inc(&quot;likenum&quot;,1);<br> update.inc(&quot;likenum&quot;);<br> //参数1:查询对象<br> //参数2:更新对象<br> //参数3:集合的名字或实体类的类型Comment.class<br> mongoTemplate.updateFirst(query,update,&quot;comment&quot;);<br>}<br>(2)测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em></li> <li>点赞数+1<br>*/<br>@Test<br>public void testUpdateCommentLikenum(){<br> //对3号文档的点赞数+1<br> commentService.updateCommentLikenum(&quot;3&quot;);<br>}<br>执行测试用例后,发现点赞数+1了:<br><img src="https://ucc.alicdn.com/pic/developer-ecology/ifuxgytxbekgq_872bf52a411e4eea8b98e7aa598f87ad.png" alt="image.png"></li> </ul>

相关文章
|
人工智能 机器人 测试技术
【python】python小游戏——开心消消乐(源码)【独一无二】
【python】python小游戏——开心消消乐(源码)【独一无二】
|
编解码 安全 搜索推荐
还没适配 Android 12 的要抓紧了(下)
还没适配 Android 12 的要抓紧了(下)
2918 0
还没适配 Android 12 的要抓紧了(下)
|
算法 应用服务中间件 Go
国密算法证书及CFCA操作流程
国密算法证书及CFCA操作流程
5473 0
|
2月前
|
弹性计算 人工智能 运维
深度解析:阿里云服务器操作系统与镜像选择指南及注意事项
阿里云ECS镜像分五类:公共镜像(官方正版、干净系统,Windows Server境外版、Red Hat、SUSE及Alibaba Cloud Linux 3/4 Pro等商业版需付费)适合自主可控;自定义镜像用于环境固化复用;共享镜像实现跨账号受控协作;镜像市场提供开箱即用的预装应用;社区镜像完全公开、平台不背书,仅供学习试验。选型应先定运维范式、再匹配镜像类型,最后校验授权成本、来源安全与生命周期三项约束,并优先选用Alibaba Cloud Linux、及时迁移停服族系。
|
5月前
|
弹性计算 人工智能 应用服务中间件
从0到1在云端部署Web应用:阿里云ECS全场景实战指南与2026省钱完全攻略
本文作者为阿里云云大使,基于真实部署经验,详解2026年阿里云服务器选型与实战:轻量服务器38元/年、ECS经济型99元/年,新用户享300元试用金+首购1折。涵盖博客、API、AI、电商等12类场景部署方案及安全、监控、成本优化技巧。(240字)
|
12月前
|
SQL 自然语言处理 安全
从“被动防御”到“主动可控”,Data Agent 如何实现精细化权限管控?
让企业敢于将数据分析能力开放给更多角色,在保障安全合规的前提下,充分释放数据价值,驱动业务创新。
|
Python
OSError: cannot open resource
【9月更文挑战第20天】
1424 3
|
开发框架 Prometheus 监控
SpringCloud微服务实战——搭建企业级开发框架(四十四):【微服务监控告警实现方式一】使用Actuator + Spring Boot Admin实现简单的微服务监控告警系统
 业务系统正常运行的稳定性十分重要,作为SpringBoot的四大核心之一,Actuator让你时刻探知SpringBoot服务运行状态信息,是保障系统正常运行必不可少的组件。 spring-boot-starter-actuator提供的是一系列HTTP或者JMX监控端点,通过监控端点我们可以获取到系统的运行统计信息,同时,我们可以自己选择开启需要的监控端点,也可以自定义扩展监控端点。 Actuator通过端点对外暴露的监控信息是JSON格式数据,我们需要使用界面来展示,目前使用比较多的就是Spring Boot Admin或者Prometheus + Grafana的方式
2394 57
|
数据采集 人工智能 算法
资深博导:我以为数据预处理是常识,直到遇到自己的学生
**摘要:** 本文介绍如何使用Python对近红外光谱土壤数据进行预处理,包括MSC(多元散射校正)、SNV(标准正规化变换)、光谱微分、基线校正和去趋势。通过代码示例展示了预处理步骤,以及每种方法前后的光谱对比。预处理旨在减少噪音、消除散射效应、基线漂移和趋势,提高数据质量和可比性,以利于后续的分析和建模。每部分都配有图表,显示了处理前后的光谱变化。
1580 0
资深博导:我以为数据预处理是常识,直到遇到自己的学生
|
小程序 JavaScript Java
人事|人事管理系统|基于Springboot的人事管理系统设计与实现(源码+数据库+文档)
人事|人事管理系统|基于Springboot的人事管理系统设计与实现(源码+数据库+文档)
839 1