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.pswp.cn/news/40062.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/40062.shtml
英文地址,請注明出處:http://en.pswp.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流并推流到流媒體服務器。 如果在其它業務場景…