MongoDB Java实战

news/2024/7/27 9:06:17/文章来源:https://blog.csdn.net/studycodeday/article/details/136458086
在这里插入图片描述

📕作者简介: 过去日记,致力于Java、GoLang,Rust等多种编程语言,热爱技术,喜欢游戏的博主。
📗本文收录于MongoDB系列,大家有兴趣的可以看一看
📘相关专栏Rust初阶教程、go语言基础系列、spring教程等,大家有兴趣的可以看一看
📙Java并发编程系列,设计模式系列、go web开发框架 系列正在发展中,喜欢Java,GoLang,Rust,的朋友们可以关注一下哦!


@[TOC] ## 实战 ## 表结构 存放文章评论的数据存放到MongoDB中,数据结构参考如下: 数据库:articledb
专栏文章评论comment
字段名称字段含义字段类型备注
_idIDObjectId或StringMongo的主键字段
articleid文章IDString
content评论内容String
userid评论人IDString
nickname评论人昵称String
createdatetime评论的日期时间Date
likenum点赞数Int32
replynum回复数Int32
state状态String0:不可见;1:可见
parentid上级IDString如果为0表示文章的顶级评论

项目搭建

<?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# 默认端口是27017port: 27017username: rootpassword: "123456"authentication-database: admin #必须设置设置权限认证的数据库

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

package onenewcode.article;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic 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 {@Autowiredprivate CommentRepository commentRepository;@Autowiredprivate MongoTemplate mongoTemplate;/*** 保存一个评论* @param comment*/public void saveComment(Comment comment){//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键//设置一些默认初始值。。。//调用daocommentRepository.save(comment);}/*** 更新评论* @param comment*/public void updateComment(Comment comment){//调用daocommentRepository.save(comment);}/*** 根据id删除评论* @param id*/public void deleteCommentById(String id){//调用daocommentRepository.deleteById(id);}/*** 查询所有评论* @return*/public List<Comment> findCommentList(){//调用daoreturn commentRepository.findAll();}/*** 根据id查询评论* @param id* @return*/public Comment findCommentById(String id){//调用daoreturn 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;//评论的业务层
@Servicepublic class CommentService {//注入dao@Autowiredprivate CommentRepository commentRepository;/*** 保存一个评论* @param comment*/public void saveComment(Comment comment){//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键//设置一些默认初始值。。。//调用daocommentRepository.save(comment);}/*** 更新评论* @param comment*/public void updateComment(Comment comment){//调用daocommentRepository.save(comment);}/*** 根据id删除评论* @param id*/public void deleteCommentById(String id){//调用daocommentRepository.deleteById(id);}/*** 查询所有评论* @return*/public List<Comment> findCommentList(){//调用daoreturn commentRepository.findAll();}/*** 根据id查询评论* @param id* @return*/public Comment findCommentById(String id){//调用daoreturn 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@Autowiredprivate CommentService commentService;/*** 保存一个评论*/@Testpublic 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);}/*** 查询所有数据*/@Testpublic void testFindAll(){List<Comment> list = commentService.findCommentList();System.out.println(list);}/*** 测试根据id查询*/@Testpublic 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查询子评论的分页列表*/@Testpublic 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@Autowiredprivate 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.classmongoTemplate.updateFirst(query,update,"comment");
}
  1. 测试用例:
 /*** 点赞数+1*/@Testpublic void testUpdateCommentLikenum(){//对3号文档的点赞数+1commentService.updateCommentLikenum("3");}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_998367.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

蓝色经典免费wordpress模板主题

蓝色经典配色的免费wordpress建站主题&#xff0c;万能的wordpress建站主题。 https://www.wpniu.com/themes/24.html

S4---FPGA-K7板级原理图硬件实战

视频链接 FPGA-K7板级系统硬件实战01_哔哩哔哩_bilibili FPGA-K7板级原理图硬件实战 基于XC7K325TFFG900的FPGA硬件实战框图 基于XILINX 的KINTEX-7 芯片XC7K325FPGA的硬件平台&#xff0c;FPGA 开发板挂载了4 片512MB 的高速DDR3 SDRAM 芯片&#xff0c;另外板上带有一个SODIM…

kafka查看消息两种方式(命令行和软件)+另附发送消息方式

1、命令行方式 ①找到kafka安装文件夹 ②执行命令 #指定offset为指定时间作为消息起始位置 kafka-consumer-groups.sh \ --bootstrap-server 20.2.246.116:9092 \ --group group_1 \ --topic lanxin_qiao \ --reset-offsets \ --to-datetime 2023-07-19T01:00:00.000 \ -exe…

软件测试工程师必备的27个基础技能

混迹于软件测试这么长时间了&#xff0c;一直想写一篇关于软件测试的经验分享的文章&#xff0c;但苦于工作原因迟迟未下笔。最近终于有了些闲余时间&#xff0c;遂决定把自己的心路历程及所感所想记录下来&#xff0c;与各位同行共勉。 以我多年的工作经验来看&#xff0c;软…

图文并茂的讲清楚Linux零拷贝技术

今天我们来聊一聊Linux零拷贝技术&#xff0c;今天我们以一个比较有代表性的技术sendfile系统调用为切入点&#xff0c;详细介绍一下零拷贝技术的原理。 1.零拷贝技术简介 Linux零拷贝技术是一种优化数据传输的技术&#xff0c;它可以减少数据在内核态和用户态之间的拷贝次数&…

乐得瑞 1C to 2C快充线:引领充电数据线新潮流,高效快充解决接口难题

随着科技的不断进步&#xff0c;数据线的接口种类也日渐繁多&#xff0c;但在早些时候&#xff0c;三合一和二合一的数据线因其独特的设计而备受欢迎。这类数据线通常采用USB-A口作为输入端&#xff0c;并集成了Micro USB、Lightning以及USB-C三种接口&#xff0c;满足了当时市…

JeecgBoot Vue3前端项目性能优化按需加载方案

JeecgBoot vue3前端项目在 3.5.5 版本之前&#xff0c;的确存在很严重的性能问题&#xff0c;大家可以参考以下文档进行升级。 按需加载改造方法 1、全局注册地方去掉2、组件改成异步注册3、用不到的大组件可以删掉 【精简项目方案】 大组件 1、富文本 tinyme2、Markdown3、…

数据库压力测试方法概述

一、前言 在前面的压力测试过程中&#xff0c;主要关注的是对接口以及服务器硬件性能进行压力测试&#xff0c;评估请求接口和硬件性能对服务的影响。但是对于多数Web应用来说&#xff0c;整个系统的瓶颈在于数据库。 原因很简单&#xff1a;Web应用中的其他因素&#xff0c;…

C++ · 代码笔记5 · 探索多态与虚函数

目录 前言011虚函数_使用基类指针实现覆盖特性012虚函数_使用引用实现覆盖特性013使用多态场景小例程020构成多态的条件030虚析构函数040纯虚函数051typeinfo运算符_获取类型信息052typeinfo_根据不同类型进行不同操作 前言 本笔记所涉及到的编程环境与 《C 代码笔记1 从C到C…

9道软件测试面试题,刷掉90%的测试程序员

没点真本事真技术&#xff0c;没点面试经验&#xff0c;不了解点职场套路&#xff0c;如何过五关斩六将&#xff1f;如何打败面试官&#xff1f;如何拿下那梦寐以求的offer&#xff1f; 如果你的跳槽意向已经很确定&#xff0c;那么请往下看&#xff01; 跳槽最重要的一步自然…

完美解决VMware中配置suse10虚拟机网络

一、注意&#xff01;&#xff01;&#xff01;配置suse10网络&#xff0c;需要在虚拟机关机状态下进行&#xff0c;否则会配置不成功&#xff1b; 二、配置与主机在同一网段(仅主机模式&#xff0c;网卡一)&#xff1b; 在suse系统关机状态下&#xff0c;Vmware中设置”虚拟网…

UE5 文字游戏(2) C++实时读取CSV文件(游戏开始读取本地CSV剧本)

1.结构体代码 // Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h" #include "Engine/DataTable.h" #include "MyCharacterStats.generated.h"USTRUCT(BlueprintType) struc…

记录 android studio 通过安装NDK 编译C文件,得到需要的so文件

只怪自己太健忘&#xff0c;每次网上查了一圈&#xff0c;搞定后&#xff0c;再遇到又发现不会操作了&#xff0c;特此记下 不废话直接上步骤 &#xff08;1&#xff09; 进入AS的settinging如下界面 &#xff08;2&#xff09;选中图片箭头两个文件 进行下载 &#xff08;…

ChatGPT高效提问——角色提示

ChatGPT高效提问——角色提示 角色提示技巧是一种通过给模型提供具体的角色扮演&#xff0c;指导ChatGPT输出的方法。这个技巧对一个具体的上下文或者听众定制生成的文本很有用。 要使用角色提示技巧&#xff0c;你需要提供明确具体的模型扮演的角色。 例如&#xff0c;如果…

docker 数据卷 详解与实践

常见的数据卷命令 命令 说明 文档地址 docker volume create 创建数据卷 docker volume create docker volume ls 查看所有数据卷 docs.docker.com docker volume rm 删除指定数据卷 docs.docker.com docker volume inspect 查看某个数据卷的详情 docs.docker.co…

【Python】6. 基础语法(4) -- 列表+元组+字典篇

列表和元组 列表是什么, 元组是什么 编程中, 经常需要使用变量, 来保存/表示数据. 如果代码中需要表示的数据个数比较少, 我们直接创建多个变量即可. num1 10 num2 20 num3 30 ......但是有的时候, 代码中需要表示的数据特别多, 甚至也不知道要表示多少个数据. 这个时候,…

qtvs2022工程cmakelist.txt添加QCharts模块

find_package(QT NAMES Qt5 COMPONENTS Core Gui Widgets OpenGL Concurrent Charts Sql Network REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui Widgets OpenGL Charts Concurrent Sql Network REQUIRED)这里find_package只是设置搜索路径&#xff0c;为…

阿里云服务器怎么使用?3分钟搭建网站教程2024新版

使用阿里云服务器快速搭建网站教程&#xff0c;先为云服务器安装宝塔面板&#xff0c;然后在宝塔面板上新建站点&#xff0c;阿里云服务器网aliyunfuwuqi.com以搭建WordPress网站博客为例&#xff0c;来详细说下从阿里云服务器CPU内存配置选择、Web环境、域名解析到网站上线全流…

【代码随想录算法训练营Day33】1005.K次取反后最大化的数组和;134.加油站;135.分发糖果

❇️Day 33 第八章 贪心算法 part03 ✴️今日任务 1005.K次取反后最大化的数组和134.加油站135.分发糖果 ❇️1005. K次取反后最大化的数组和 本题简单一些&#xff0c;估计大家不用想着贪心 &#xff0c;用自己直觉也会有思路。题目链接&#xff1a;https://leetcode.cn/pr…

如何在Windows上使用Docker,搭建一款实用的个人IT工具箱It- Tools

文章目录 1. 使用Docker本地部署it-tools2. 本地访问it-tools3. 安装cpolar内网穿透4. 固定it-tools公网地址 本篇文章将介绍如何在Windows上使用Docker本地部署IT- Tools&#xff0c;并且同样可以结合cpolar实现公网访问。 在前一篇文章中我们讲解了如何在Linux中使用Docker搭…