spring boot 整合mongodb

1、安装依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>

2、配置数据库连接

spring:data:mongodb:host: localhostport: 27017username: xxxxxxpassword: xxxxxxdatabase: xxxxxxauthentication-database: admin

3、新建实体类

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;@Data
//代表集合名称
@Document("myCollection")
public class MyCollection {@Idprivate String id;private String name;private Integer age;private String sex;
}

4、调用方法
4.1 方法一

package com.example.springboot3test.controller;import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.*;import java.util.List;
import java.util.regex.Pattern;@RestController
@RequestMapping("/test")
public class TestController {@Resourceprivate MongoTemplate mongoTemplate;//引入的对象//查询所有不带条件@GetMapping("/findAllData")public List<MyCollection> findAllData(){return mongoTemplate.findAll(MyCollection.class);}//根据Id查询@GetMapping("/findDataById/{id}")public MyCollection findDataById(@PathVariable("id") String id){return mongoTemplate.findById(id,MyCollection.class);}//where条件查询@PostMapping("/findByWhere")public List<MyCollection> findByWhere(@RequestBody MyCollection myCollection){Query query=new Query(Criteria.where("name").is(myCollection.getName()).and("age").gte(myCollection.getAge()));return mongoTemplate.find(query,MyCollection.class);}//模糊查询@PostMapping("/findByLike")public List<MyCollection> findByLike(@RequestBody MyCollection myCollection){String regex = String.format("%s%s%s", "^.*", myCollection.getName(), ".*$");Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);Query query=new Query(Criteria.where("name").regex(pattern));return mongoTemplate.find(query,MyCollection.class);}//插入@PostMapping("/insertMongodb")public String insertMongodb(@RequestBody MyCollection myCollection){mongoTemplate.insert(myCollection);return "OK";}//批量插入@PostMapping("/insertBatchsMongodb")public String insertBatchsMongodb(@RequestBody List<MyCollection> list){mongoTemplate.insertAll(list);return "OK";}//更新@PostMapping("/updateMongodb")public String updateMongodb(@RequestBody MyCollection myCollection){Query query=new Query(Criteria.where("age").gte(38));Update update=new Update();update.set("name",myCollection.getName());//单条更新//mongoTemplate.upsert(query,update,MyCollection.class);//批量更新mongoTemplate.updateMulti(query,update,MyCollection.class);return "OK";}//删除根据条件@GetMapping("/deleteMongodb/{age}")public String deleteMongodb(@PathVariable("age") Long age){Query query=new Query(Criteria.where("age").gte(age));mongoTemplate.remove(query,MyCollection.class);return "OK";}
}

注:其中的常用方法如下

常用方法
mongoTemplate.findAll(User.class): 查询User文档的全部数据
mongoTemplate.findById(<id>, User.class): 查询User文档id为id的数据
mongoTemplate.find(query, User.class);: 根据query内的查询条件查询
mongoTemplate.upsert(query, update, User.class): 修改
mongoTemplate.remove(query, User.class): 删除
mongoTemplate.insert(User): 新增Query对象
1、创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)
2、 精准条件:criteria.and(“key”).is(“条件”)模糊条件:criteria.and(“key”).regex(“条件”)
3、封装条件:query.addCriteria(criteria)
4、大于(创建新的criteria):Criteria gt = Criteria.where(“key”).gt(“条件”)小于(创建新的criteria):Criteria lt = Criteria.where(“key”).lt(“条件”)
5、Query.addCriteria(new Criteria().andOperator(gt,lt));
6、一个query中只能有一个andOperator()。其参数也可以是Criteria数组。
7、排序 :query.with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))

Criteria查询条件类常用方法

//声明定义查询条件,且为静态方法
where(String key)
//与操作
and(String key)
//正则表达式,即可为模糊查询
regex(String re)
//包含
in(Object... o)    
//大于
gt(Object o)
//大于等于
gte(Object o)
//等于
is(Object o)
//小于
lt(Object o)
//小于等于
lte(Object o) 
//非
not()
//创建与操作
andOperator(Criteria... criteria) 

4.2 方法二 spring Data 方式
spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类,按照Spring Data规范就可以了。
当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By + 属性名(首字母大写)
在这里插入图片描述
在这里插入图片描述

step1 新建MyCollectionRepository接口

package com.example.springboot3test.dao;import com.example.springboot3test.entity.MyCollection;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface MyCollectionRepository extends MongoRepository<MyCollection,String> {//当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By +// 属性名(首字母大写),如:根据姓名查询Person。//仓库中添加的方法//根据名称查询List<MyCollection> findByName(String name);//模糊查询List<MyCollection> findByNameLike(String name);//模糊查询List<MyCollection> findByNameLikeAndAgeGreaterThanEqual(String name,Integer age);}

step2 、测试代码

package com.example.springboot3test.controller;import com.example.springboot3test.dao.MyCollectionRepository;
import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/mongodb")
public class TestMongodbController {@Resourceprivate MyCollectionRepository myCollectionRepository;//插入单条@PostMapping("/insertMongodb")public String insertMongodb(@RequestBody MyCollection myCollection){myCollectionRepository.insert(myCollection);return "OK";}//批量插入@PostMapping("/insertMongodbBatchs")public String insertMongodbBatchs(@RequestBody List<MyCollection> myCollection){myCollectionRepository.insert(myCollection);return "OK";}//更新@PostMapping("/updateMongodb")public String updateMongodb(@RequestBody MyCollection myCollection){myCollectionRepository.save(myCollection);//myCollectionRepository.insert(myCollection);return "OK";}//删除@GetMapping("/deleteMongodbById/{id}")public String deleteMongodbById(@PathVariable("id") String id){myCollectionRepository.deleteById(id);return "OK";}//查询所有@GetMapping("/findAll")public List<MyCollection> findAll(){return myCollectionRepository.findAll();}//根据Id进行查询@GetMapping("/findById/{id}")public MyCollection findById(@PathVariable("id") String id){return myCollectionRepository.findById(id).get();}//条件查询@PostMapping("/findQuery")public List<MyCollection> findQuery(@RequestBody MyCollection myCollection){//Example<MyCollection> example=Example.of(myCollection);return myCollectionRepository.findByName(myCollection.getName());}//模糊匹配@PostMapping("/findLike")public List<MyCollection> findLike(@RequestBody MyCollection myCollection){
//        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
//                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
//                .withIgnoreCase(true);//改变默认大小写忽略方式:忽略大小写
//        Example<MyCollection> example=Example.of(myCollection,matcher);return myCollectionRepository.findByNameLike(myCollection.getName());//单个模糊查询}//模糊匹配@PostMapping("/findLikeAnd")public List<MyCollection> findLikeAnd(@RequestBody MyCollection myCollection){
//        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
//                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
//                .withIgnoreCase(true);//改变默认大小写忽略方式:忽略大小写
//        Example<MyCollection> example=Example.of(myCollection,matcher);//多个条件模糊查询return myCollectionRepository.findByNameLikeAndAgeGreaterThanEqual(myCollection.getName(),myCollection.getAge());}}

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

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

相关文章

2682. 找出转圈游戏输家

题目描述&#xff1a; n 个朋友在玩游戏。这些朋友坐成一个圈&#xff0c;按 顺时针方向 从 1 到 n 编号。从第 i 个朋友的位置开始顺时针移动 1 步会到达第 (i 1) 个朋友的位置&#xff08;1 < i < n&#xff09;&#xff0c;而从第 n 个朋友的位置开始顺时针移动 1 步…

“华为杯”研究生数学建模竞赛2018年-【华为杯】F题:中转航班调度:从 MILP 模型到启发式算法

目录 摘 要 1 问题描述 2 模型假设 3 符号定义及数据预处理 3.1 符号定义

【广州华锐视点】帆船航行VR模拟实操系统

帆船航行VR模拟实操系统由广州华锐视点开发&#xff0c;是一种创新的教学工具&#xff0c;它利用虚拟现实技术&#xff0c;为学生提供了一个沉浸式的学习环境。通过这种系统&#xff0c;学生可以在虚拟的环境中进行帆船航行的实训&#xff0c;从而更好地理解和掌握帆船航行的技…

Maven(四)常用命令大全

目录 一、mvn 命令参数二、mvn 插件命令1.介绍2.查看插件的使用文档3.常用的插件命令 官网地址&#xff1a; https://maven.apache.org/官方插件清单&#xff1a; https://maven.apache.org/plugins/index.html Maven 是一个强大的构建工具&#xff0c;它提供了许多命令来进行项…

使用Python统计字符内容的占比

说明&#xff1a;如果有自己动手做过字符动画&#xff0c;会知道字符动画的“灵动性”核心在于使用的字符集。 简单来说&#xff0c;动画转为字符动画&#xff0c;原理是将动画转为灰阶图&#xff0c;灰度范围是0~255&#xff0c;然后将对应灰度的像素点转为对应比值的字符。这…

linux github 仓库管理常用操作

linux 的常用操作 linux 本地 ssh验证连接github账号本地仓库连接远程私有仓库push/pull操作 Connecting to Github with ssh git local configuration If you are using git for the first time, configure the user name and email in the device. git config --global u…

R语言ggplot2 | R语言绘制物种组成面积图(三)

&#x1f4cb;文章目录 面积图简介准备数据集加载数据集数据处理数据可视化 利用R语言绘制物种组成图。本文以堆叠面积图的方式与大家分享。 面积图简介 面积图又叫区域图。它是在折线图的基础之上形成的, 它将折线图中折线与自变量坐标轴之间的区域使用颜色或者纹理填充&…

设计模式之单例设计模式

单例设计模式 2.1 孤独的太阳盘古开天&#xff0c;造日月星辰。2.2 饿汉造日2.3 懒汉的队伍2.4 大道至简 读《秒懂设计模式总结》 单例模式(Singleton)是一种非常简单且容易理解的设计模式。顾名思义&#xff0c;单例即单一的实例&#xff0c;确切地讲就是指在某个系统中只存在…

【算法题】螺旋矩阵III (求解n阶蛇形矩阵)

一、问题的提出 n阶蛇形矩阵的特点是按照图1所示的方式排列元素。n阶蛇形矩阵是指矩阵的大小为nn&#xff0c;其中n为正整数。 题目背景 一个 n 行 n 列的螺旋矩阵可由如图1所示的方法生成&#xff0c;观察图片&#xff0c;找出填数规律。填数规则为从 1 开始填到 nn。 图1 …

【配置环境】Linux下安装MySQL

目录 一&#xff0c;环境 二&#xff0c;安装步骤 1.使用包管理器安装MySQL 2.配置MySQL的安全选项 3.设置root用户使用密码进行身份验证&#xff08;可选&#xff09; 三&#xff0c;拓展知识 1.如何修改MySQL的密码策略&#xff1f; 2.实现连接MySQL数据库的测试代码…

TiDB基础介绍、应用场景及架构

1. 什么是newsql NewSQL 是对各种新的可扩展/高性能数据库的简称&#xff0c;这类数据库不仅具有NoSQL对海量数据的存储管理能力&#xff0c;还保持了传统数据库支持ACID和SQL等特性。 NewSQL是指这样一类新式的关系型数据库管理系统&#xff0c;针对OLTP&#xff08;读-写&…

经验分享:企业数据仓库建设方案总结!

导读 在企业的数字化转型浪潮中&#xff0c;数据被誉为“新时代的石油”&#xff0c;而数据仓库作为数据管理与分析的核心基础设施&#xff0c;在企业的信息化建设中扮演着重要的角色。本文将深入探讨企业数据仓库建设过程中所遇到的问题以及解决经验&#xff0c;为正在筹备或…

进程/线程上下文切换会用掉你多少CPU?

进程是操作系统的伟大发明之一&#xff0c;对应用程序屏蔽了CPU调度、内存管理等硬件细节&#xff0c;而抽象出一个进程的概念&#xff0c;让应用程序专心于实现自己的业务逻辑既可&#xff0c;而且在有限的CPU上可以“同时”进行许多个任务。但是它为用户带来方便的同时&#…

嵌入式Linux Qt5 (C++)开发栏目概述

本栏目开始介绍Linux系统下的Qt C程序开发&#xff0c;资源是以嵌入式为切入点&#xff08;现在Linux系统下的Qt C程序开发好像就是应用于嵌入式&#xff09;&#xff0c;那就跟着一起学习Linux系统下的Qt C程序开发知识&#xff0c;再扩展一下嵌入式的知识吧。我这里默认已经熟…

php初解

php是什么&#xff1f; PHP&#xff0c;全称 Hypertext Preprocessor &#xff0c;中文翻译“超文本预处理器”。 PHP是一种被广泛应用的开源通用脚本语言&#xff0c;尤其适用于 Web 开发。 拥有快速&#xff0c;灵活&#xff0c;实用的特点&#xff0c;PHP能做任何事&#xf…

ORACLE中UNION、UNION ALL、MINUS、INTERSECT学习

1、UNION和UNION ALL的使用与区别 如果我们需要将两个select语句的结果作为一个整体显示出来&#xff0c;我们就需要用到union或者union all关键字。union的作用是将多个结果合并在一起显示出来。 union和union all的区别是union会自动压缩多个结果集合中的重复结果&#xff…

高速下载VisualGLM模型文件的解决方案

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

GO语言自底向上优化

Go Ballast(通过尝试降低 GC 频率以提高整体性能&#xff0c;针对所有 Go应用都适用) 首先我们明白GO语言GC触发条件是由比例来触发的。例如&#xff0c;当前存活内存10GB&#xff0c;触发比例是100%&#xff0c;因此下次触发GC的时候是当内存达到20GB的时候触发GC。这种机制在…

碎片笔记|图数据与图神经网络基础介绍

前言&#xff1a;前段时间了解了一下图神经网络&#xff0c;本篇博客记录一下相关知识&#xff0c;以备不时之需。 强烈推荐这篇博客&#xff08;作者来自 Google Research&#xff09;&#xff0c;个人认为是图神经网络基础入门的不二选择&#xff01; 目录 一、图数据1.1 定义…

Windows上使用FFmpeg实现本地视频推送模拟海康协议rtsp视频流

场景 Nginx搭建RTMP服务器FFmpeg实现海康威视摄像头预览&#xff1a; Nginx搭建RTMP服务器FFmpeg实现海康威视摄像头预览_nginx rtmp 海康摄像头_霸道流氓气质的博客-CSDN博客 上面记录的是使用FFmpeg拉取海康协议摄像头的rtsp流并推流到流媒体服务器。 如果在其它业务场景…