spring boot MongoDB实战

项目搭建

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>itcast</groupId>
    <artifactId>article</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
 
    </dependencies>
 </project>

(2)创建application.yml

spring:
  #数据源配置
  data:
    mongodb:
      # 主机地址
      host: 192.168.218.131
      # 数据库
      database: articledb
      # 默认端口是27017
      port: 27017
      username: root
      password: "123456"
      authentication-database: admin #必须设置设置权限认证的数据库

(3)创建启动类
onenewcode.article.ArticleApplication

package onenewcode.article;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
 public class ArticleApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ArticleApplication.class, args);
    }
 }

(4)启动项目,看是否能正常启动,控制台没有错误。

文章评论实体类的编写

创建实体类 创建包onenewcode.article,包下建包po用于存放实体类,创建实体类
onenewcode.article.po.Comment

package onenewcode.article.service;

import onenewcode.article.dao.CommentRepository;
import onenewcode.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 保存一个评论
     * @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();
    }


    public Page<Comment> findCommentListByParentid(String parentid,int page,int size) {
        return commentRepository.findByParentid(parentid,PageRequest.of(page-1,size));
    }

    public void updateCommentLikenum(String id){

        //  查询条件
        Query query = Query.query(Criteria.where("_id").is(id));
        //  更新条件
        Update update = new Update();
        update.inc("likenum");
        mongoTemplate.updateFirst(query,update,Comment.class);
    }
}

**说明:**索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过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
复合索引的声明,建复合索引可以有效地提高多字段的查询效率。

db.comment.createIndex({“userid”:1,“nickname”:-1})

文章评论的基本增删改查

  1. 创建数据访问接口 onenewcode.article包下创建dao包,包下创建接口
    onenewcode.article.dao.CommentRepository
package onenewcode.article.dao;
 
import onenewcode.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<Comment,String> {
  
}
  1. 创建业务逻辑类 onenewcode.article包下创建service包,包下创建类
import onenewcode.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();
    }
 }
  1. 新建Junit测试类,测试保存和查询所有:
package onenewcode.article.service;
 
import onenewcode.article.ArticleApplication;
import onenewcode.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集成测试
 //SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest
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);
    }
}

添加结果:
请添加图片描述

根据上级ID查询文章评论的分页列表

  1. CommentRepository新增方法定义

//根据父id,查询子评论的分页列表
Page findByParentid(String parentid, Pageable pageable);

  1. CommentService新增方法
 /**
     * 根据父id查询分页列表
     * @param parentid
     * @param page
     * @param size
     * @return
     */
    public Page<Comment> findCommentListPageByParentid(String parentid,int page ,int size){
        return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));
    }
  1. junit测试用例
 /**
     * 测试根据父id查询子评论的分页列表
     */
    @Test
    public void testFindCommentListPageByParentid(){
        Page<Comment> pageResponse = commentService.findCommentListPageByParentid("3", 1, 2);
        System.out.println("----总记录数:"+pageResponse.getTotalElements());
        System.out.println("----当前页数据:"+pageResponse.getContent());
    }

MongoTemplate实现评论点赞

以下点赞的临时示例代码: CommentService 新增updateThumbup方法

   /**
     * 点赞-效率低
     * @param id
     */
    public void updateCommentThumbupToIncrementingOld(String id){
        Comment comment = CommentRepository.findById(id).get();
        comment.setLikenum(comment.getLikenum()+1);
        CommentRepository.save(comment);
    }

以上方法虽然实现起来比较简单,但是执行效率并不高,因为我只需要将点赞数加1就可以了,没必要查询出所有字段修改后再更新所有字
段。(蝴蝶效应)
我们可以使用MongoTemplate类来实现对某列的操作。 (1)修改CommentService

//注入MongoTemplate
    @Autowired
    private MongoTemplate mongoTemplate;
 
/**
 * 点赞数+1
 * @param id
 */
 public void updateCommentLikenum(String id){
 //查询对象
Query query=Query.query(Criteria.where("_id").is(id));
 //更新对象
Update update=new Update();
 //局部更新,相当于$set
 //        
update.set(key,value)
 //递增$inc
 //        
update.inc("likenum",1);
 update.inc("likenum");
 }
 //参数1:查询对象
//参数2:更新对象
//参数3:集合的名字或实体类的类型Comment.class
 mongoTemplate.updateFirst(query,update,"comment");
}
  1. 测试用例:
 /**
 * 点赞数+1
 */
 @Test
 public void testUpdateCommentLikenum(){
 //对3号文档的点赞数+1
 commentService.updateCommentLikenum("3");
 }

GITHUB

代码仓库

https://github.com/onenewcode/MyMongoDB.git
Spring Boot整合MongoDB实战:从CRUD到聚合查询 文档数据库作为处理非结构化数据的利器,其核心优势在于灵活的数据模型和水平扩展能力。MongoDB作为领先的NoSQL解决方案,通过BSON格式实现类JSON文档存储,特别适合用户行为日志、物联网数据等动态结构场景。Spring Data MongoDB提供的MongoTemplate组件将MongoDB的强大功能与Spring Boot的开发效率完美结合,支持从基础CRUD到复杂聚合查询的全套操作。在性能优化方面,合理使用批量操作BulkOperations和索引策略能显著提升吞吐量,而连接池配置和慢查询监 阅读详情

相关推荐

看十年架构师用Spring Boot 整合 MongoDB 实战解说

搞懂这三个名词,基本就可以上手了,今天我们以 Java 语言为例,详细地介绍 Java 客户端改如何操作 MongoDB!话不多说,直接开撸!

Java_zhujia的博客 1190

mongodb 索引详解

使用springboot连接mongodb的时候,涉及到索引的使用 举例: @Document(collection="book") //注释的是复合索引 //@CompoundIndexes( // { // @CompoundIndex(name = "复合索引名字",def = "{'字段01':1,'字段02':1}") // })...

zhangsir的博客 8603

Spring Boot与MongoDB集成实战

在现代Java开发中,Spring Boot是一个关键的框架,它简化了基于Spring的应用程序的配置和部署。Spring Boot的设计理念是约定优于配置,提供了快速启动、运行和开发应用程序的能力,特别适合微服务架构。NoSQL数据库,即非关系型数据库,以其灵活的数据模型和扩展能力在大数据时代大放异彩。它们通常不使用传统的关系数据库管理系统的表格模型,而是采用键值对、文档、列族、图形等数据模型。

weixin_30653091的博客 943

MongoDB注解@Indexed(background = true)详解

总之,注解是 Spring Data MongoDB 中非常有用的一个注解,可以帮助我们创建后台索引,提高索引创建效率并避免阻塞主线程。

new_Learn0822的博客 1547

图论:Dijkstra算法——最详细的分析,图文并茂,一次看懂!

Dijstra算法

普罗米修斯的博客 18万+

Ansys-结构动力学分析-圆柱斜齿轮模态分析学习心得

模态分析的步骤基本一直,不同点在于选择什么单元类型,模型,节点约束等 圆柱斜齿轮模态分析的难点在于圆柱斜齿轮的模型建立,和所要约束的节点的选择。 用命令流方法建立齿轮模型效率较高,当然,在ansys里建立复杂的模型实在不敢恭维,对于自下而上建模,需要知道每个关键点的坐标位置。下图是创建圆柱斜齿轮模型的命令流方式。 模型不同使用的数据也就不同了。 对于施加约束的问题这就必须要熟悉select e...

weixin_45385183的博客 1838

SpringBoot整合MongoDB

MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是可以应用于各种规模的企业、各个 行业以及各类应用程序的开源数据库。基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应 用提供可扩展的高性能数据存储解决方案。MongoDB是一个高性能,开源,无模式的文档型数据库,是当前NoSql数据库中比较热门的一种。

小名同学 21万+

RAGFlow 离线部署:解决cl100k_base.tiktoken问题

摘要 本文详细解决了RAGFlow离线部署时tiktoken缓存文件下载失败的问题。通过分析tiktoken库的缓存机制,一次性不改代码解决.

baidu_25691461的博客 843

MongoDB, SpringBoot中MongoDB注解概念及使用

/在 java bean 中字段名为 userName,存储到 mongo 中 key 为 user_name。标注在实体类上,把ava类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。对关联的对象的字段进行索引,譬如User对关联的address.city进行索引。如果自己设置@Id主键,并标注在自定义的列名上,需要自己生成并维护不重复的约束。对数组进行索引,MongoDB会索引这个数组中的每一个元素。// 数字参数指定索引的方向,1为正序,-1为倒序。

Mr. David 专栏 3548

c#.net使用正则表达式验证文本中是否包含手机号码或电话号码?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Collections; namespace RegularPhoneApp { class Program

码农 3591

23数字图像置乱技术(matlab程序)

所谓“置乱”,就是将图像的信息次序打乱,a像素移动到b像素位置上,b像素移动到c像素位置上,……,使其变换成杂乱无章难以辨认的图片。数字图像置乱技术属于加密技术,是指发送发借助数学或者其他领域的技术,对一幅有意义的数字图像做变换,使之变成一幅杂乱无章的图像用于传输。在图像传输过程中,它通过对图像像素矩阵的重排,破坏了图像矩阵的相关性,使非法截获者无法从杂乱无章的图像中获得原图像信息,以此实现信息的加密。接收方经去乱解密可恢复原图像。

m0_57943157的博客 1215

SpringBoot整合MongoDB 及 基本使用

SpringBoot整合MongoDB及基本Api

weixin_50769390的博客 2394

COLMAP生成MVSNet数据集

COLMAP生成MVSNet数据集

qq_43307074的博客 5650

Spring Boot中MongoDB的使用和实战

Spring Boot中MongoDB的使用和实战 附有源码 讲解详细

showswoller的博客 2739

解放双手,摆脱自建库的繁琐,立创EDA元件库转cadence原理图封装库实战技巧

解放双手,摆脱自建库的繁琐,立创EDA元件库转cadence原理图封装库实战技巧

u012790770的博客 3653

【WRF理论第十四期】 VEGPARM.TBL 文件详解

WRF 读取 VEGPARM.TBL 文件

WW、forever的博客 579

Spring Boot中使用MongoDB数据库实战

 一 MongoDB简介 MongoDB是一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库之间的产品,其主要目标是在键/值存储方式(提供了高性能和高度伸缩性)和传统的RDBMS系统(具有丰富的功能)之间架起一座桥梁,它集两者的优势于一身。 MongoDB支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型,也因为他的存储格式也使得它所存储的数...

实践求真知 852

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Spring Boot集成MongoDB及实战技巧与性能调优

通过以上步骤与技巧,可高效集成MongoDB并优化应用性能。实际项目中需结合监控工具(如MongoDB Atlas、Spring Boot Actuator)持续分析调整。

bsklhao的博客 1428

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Spring Boot与MongoDB整合实战指南

Spring Boot与MongoDB整合实战指南 项目介绍 Spring Boot MongoDB 是一个基于 Spring Boot 框架和 MongoDB 数据库的示例项目。该项目展示了如何利用 Spring Data MongoDB 模块轻松集成 MongoDB,实现数据的增删查改操作。它旨在提供一个简洁明了的起点,帮助开发者快速上手在 Spring Boot 应用中使用 MongoDB...

gitblog_00134的博客 523

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Spring Boot下MongoDB实战

一 安装MongoDB 1 Docker安装 安装完成后,执行下面命令: docker run -d -p 27017:27017 mongo 2 VirtualBox下做一次端口映射 3 下载MongoDB数据库管理软件Robomongo 下载地址 http://www.robomongo.org 二 新建Spring Boot项目 新增依赖 &lt;dependen...

实践求真知 774

Spring Boot 与 MongoDB 集成实战

Id@DBRef@IdSpring Boot 与 MongoDB 的集成非常顺畅,通过 Spring Data MongoDB,我们可以快速构建基于文档数据库的应用。在实际项目中,我们应该合理设计文档结构,充分利用 MongoDB 的特性,这其实可以更优雅一点。如果有任何问题或建议,欢迎在评论区留言,我会认真回复每一条评论。希望这篇文章对大家有所帮助。

alex_goden的博客 3997

Spring Boot整合MongoDB实战指南

MongoDB作为主流的NoSQL数据库,以其灵活的文档模型和高性能著称。其核心原理基于BSON格式存储数据,支持动态schema设计,特别适合处理非结构化数据。在Java生态中,Spring Data MongoDB通过MongoTemplate和Repository抽象层,显著简化了开发流程。本文以博客系统为例,详细演示环境搭建、CRUD优化、聚合查询等实战技巧,涵盖索引优化、事务管理等进阶主题,帮助开发者快速掌握Spring Boot与MongoDB的整合方案。

weixin_26805597的博客 301

Spring Boot 整合 MongoDB 实战

通过本文的学习,我们了解了如何使用Spring Boot整合MongoDB。首先我们完成了环境的准备,包括安装配置Java开发环境和MongoDB数据库,并创建了一个Spring Boot项目。然后我们添加了MongoDB的依赖,并在配置文件中配置了MongoDB的连接信息。接着我们创建了MongoDB的实体类,并使用注解定义了实体类和集合的映射关系。然后我们编写了MongoDB Repository接口,并使用Spring Data MongoDB提供的方法来进行CRUD操作。

博客 744

Spring Boot 实战 :集成 MongoDB

阿里伤透我心,疯狂复习刷题,终于喜提offer 哈哈~好啦,不闲扯了1、JAVA面试核心知识整理(PDF):包含JVMJAVA集合JAVA多线程并发,JAVA基础,Spring原理微服务,Netty与RPC,网络,日志,ZookeeperKafkaRabbitMQ,Hbase,MongoDB设计模式负载均衡数据库一致性哈希JAVA算法数据结构,加密算法,分布式缓存,Hadoop,Spark,Storm,YARN,机器学习,云计算共30个章节。2、Redis学习笔记及学习思维脑图。

2401_86402690的博客 1422

Spring Boot 整合 MongoDB:CRUD 与聚合查询实战

Spring Boot 整合 MongoDB:CRUD 与聚合查询实战指南。文档设计原则:根据查询模式设计文档结构;合理使用嵌入和引用;控制文档大小,避免超过16MB限制;性能优化要点:为常用查询创建适当索引;使用投影减少网络传输;批量操作替代单条操作;事务使用建议:仅在必要时使用多文档事务;控制事务持续时间;处理乐观锁冲突

夜雨的博客 1185

Spring Boot集成MongoDB实战(复合索引性能提升200%的秘密)

掌握Spring Boot MongoDB的复合索引优化技巧,显著提升查询性能。适用于高并发读写场景,通过合理创建复合索引减少查询响应时间达200%。详解配置方法与最佳实践,有效降低数据库负载。值得收藏,点击了解实战细节。

AlgoFun的博客 691
上一篇: spring boot整合MongoDB 一
下一篇: rust 全局变量
过去日记
过去日记 新星创作者: 后端开发技术领域 新星创作者: 后端开发技术领域
博客等级 码龄3年 5344粉丝 225原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

过去日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址