Spring boot整合Mongodb

最近的項目用了Mongodb,網上的用法大多都是七零八落的沒有一個統一性,自己大概整理了下,項目中的相關配置就不敘述了,由于spring boot的快捷開發方式,所以spring boot項目中要使用Mongodb,只需要添加依賴和配置application.properties文件即可。整和方式一共有兩種,一種是JPA的快捷方式,還有一種是實現MongoTemplate中的方法。

一、spring boot Mongodb JPA

  這種是mongodb的快捷開發方式,類似于spring data jpa的操作,通過使用spring boot約定的規范來定義名字,與HibernateRepository類似,通過繼承MongoRepository接口,我們可以非常方便地實現對一個對象的增刪改查,要使用Repository的功能,先繼承MongoRepository<T, TD>接口,其中T為倉庫保存的bean類,TD為該bean的唯一標識的類型,一般為ObjectId。之后在service中注入該接口就可以使用,無需實現里面的方法,spring會根據定義的規則自動生成。

創建一個bean,其中@id是這種表的主鍵,user就是表的名字

import org.springframework.data.annotation.Id;public class User  {@Idprivate Long id;private String name;private Integer userage;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getUserage() {return userage;}public void setUserage(Integer userage) {this.userage = userage;}public User(Long id, String name, Integer userage) {super();this.id = id;this.name = name;this.userage = userage;}}
View Code

通過jpa的方式實現查找,下面介紹最簡單的兩張和定義規則:

import org.springframework.data.mongodb.repository.MongoRepository;public interface UserMongodbJPA extends MongoRepository<User, Long>{
/*** * 單個條件查詢,通過名字到數據* 方法名字定義規則:*  find +By+條件字段(必須是User中的屬性)*/List<User> findByName(String name);/** * 多個條件查詢,通過年齡和名字找到數據* 方法名字定義規則:* * ind +By+條件字段(必須是User中的屬性)+AND+條件字段(必須是User中的屬性)*/List<User>  findByUserageAndName(Integer userage,String name );
}
View Code

具體的其他命名規則,可通過下面的圖進行查閱:

二、Spring boot? Mongodb原生實現方式

?    JAP的方式雖然簡單快捷,但是這種方式只能進行簡單的查詢操作,但是業務中往往需要復雜的邏輯操作,這時就不滿足我們的需求,所以使用原生的方式,就能解決復制的邏輯業務。這種方式通過繼承MongoRepository接口,只需要調用MongoTemplate中的方法即可。

  插入數據

  MongoTemplate為我們提供了兩種方法插入數據:insert和save,兩者的區別就是insert方法如果插入的數據的主鍵已經存在,則會拋出異常;save方法插入的數據的主鍵已經存在,則會對當前已經存在的數據進行修改操作。? ??

private MongoTemplate mongoTemplate;/*** insert方法,會新增一條數據*/public void insert(){User u = new User("1","zhangsan",18);mongoTemplate.insert(u);}/*** save方法,如果主鍵重復,則修改原來的數據*/public void save() {User u = new User("1","小明",19);mongoTemplate.save(u);}
View Code

?

? ? ?更新數據

? ? ?更新一條數據,在關系型數據庫中,我們需要where條件篩選出需要更新的數據,并且要給定更新的字段及值,在mongodb中也是一樣,如果要使用篩選條件,就必須實例化Query對象。

/*** 要使用原生的mongodb方式,就要創建MongoTemplate ,*他的方法來實現SQL*/
private MongoTemplate mongoTemplate;/*** 更新對象*/public void updateTest() {//用來封裝所有條件的對像Query query = new Query();//用來構建條件Criteria criteria = new Criteria();//criteria.and("你MongoDB中的key").is("你的條件")      criteria.and("name").is("小明");//把條件封裝起來   
        query.addCriteria(criteria) ;//  Update 中構建更新的內容Update update= new Update().set("userage", "15").set("name", "小紅");//更新查詢返回結果集的第一條mongoTemplate.updateFirst(query,update,MongoTest.class);//更新查詢返回結果集的所有mongoTemplate.updateMulti(query,update,User.class); 
}
View Code

? ? ?刪除數據

? ? ?刪除數據和更新數據類似,只需要使用MongoTemplate中的remove方法就能實現。

*** 刪除對象**/public void deleteTestById() {Query query=new Query(Criteria.where("name").is("小紅"));mongoTemplate.remove(query,User.class);}、
View Code

?

三、聚合操作

?  在mysql數據庫中,我們更多情況我們會使用聚合操作來簡便我們的代碼,列如SUM、count;在mongodb的數據庫中,也是有這樣的聚合函數,但是這時不在使用Query對象來封裝條件,而是使用Aggregation對象來實現聚合操作,需要注意的是:mongoTemplate.aggregate實現的方法返回的是AggregationResults對象。

    public AggregationResults<T> aggregation(int pageNum, int pageSize, Criteria criteria,String name, String sortName, Sort sort,String tableName)throws BbsException {Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),//用于過濾數據,只輸出符合條件的文檔Aggregation.group(name);//將集合中的文檔根據fileID分組,可用于統計結果。Aggregation.sort(sort), //將輸入文檔根據sort排序后輸出。Aggregation.skip(pageNum - 1) * pageSize),//在聚合管道中跳過指定數量的文檔,并返回余下的文檔。Aggregation.limit(pageSize),//用來限制MongoDB聚合管道返回的文檔數。Aggregation.sum(userage)//用來求和,求出userage字段值的和
              );return mongoTemplate.aggregate(aggregation, tableName, user.class);//tableName表示表的名字
View Code

?

?

?

?

?

?

?

?

    

轉載于:https://www.cnblogs.com/daijiting/p/10083842.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278721.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278721.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278721.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

nodejs和Vue和Idea

文章目錄Vue環境搭建Idea安裝Idea中配置Vue環境Node.js介紹npm介紹Vue.js介紹[^3]Idea介紹Vue環境搭建 概述&#xff1a;vue環境搭建&#xff1a;需要npm&#xff08;cnpm&#xff09;&#xff0c;而npm內嵌于Node.js&#xff0c;所以需要下載Node.js。 下載Node.js&#xff1…

Spring MVC上下文父子容器

2019獨角獸企業重金招聘Python工程師標準>>> Spring MVC上下文父子容器 博客分類&#xff1a; java spring 在Spring MVC的啟動依賴Spring框架&#xff0c;有時候我們在啟動Spring MVC環境的時候&#xff0c;如果配置不當的話會造成一些不可預知的結果。下面主要介紹…

12.7 Test

目錄 2018.12.7 TestA 序列sequence(迭代加深搜索)B 轟炸bomb(Tarjan DP)C 字符串string(AC自動機 狀壓DP)考試代碼AC2018.12.7 Test題目為2018.1.4雅禮集訓。 時間&#xff1a;4.5h期望得分&#xff1a;010010實際得分&#xff1a;010010 A 序列sequence(迭代加深搜索) 顯然可…

word文檔中統計總頁數_如何在Google文檔中查找頁數和字數統計

word文檔中統計總頁數Whether you’ve been given an assignment with a strict limit or you just like knowing how many words you’ve written, Google Docs has your back. Here’s how to see exactly how many words or pages you’ve typed in your document. 無論您是…

vue 入門notes

文章目錄vue一、js基礎二、封裝緩存三、組件1、組件創建、引入、掛載、使用2、組件間的傳值- 父組件主動獲取子組件的數據和方法&#xff08;子組件給父組件傳值&#xff09;&#xff1a;- 子組件主動獲取父組件的數據和方法&#xff08;父組件給子組件傳值&#xff09;&#x…

spring集成 JedisCluster 連接 redis3.0 集群

2019獨角獸企業重金招聘Python工程師標準>>> spring集成 JedisCluster 連接 redis3.0 集群 博客分類&#xff1a; 緩存 spring 客戶端采用最新的jedis 2.7 1. maven依賴&#xff1a; <dependency> <groupId>redis.clients</groupId> <artifact…

html-盒子模型及pading和margin相關

margin: <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title><style>* {margin: 0;padding: 0;}/*margin 外邊距 元素與其他元素的距離&#xff08;邊框以外的距離&#xff09;一…

火狐瀏覽器復制網頁文字_從Firefox中的網頁鏈接的多種“復制”格式中選擇

火狐瀏覽器復制網頁文字Tired of having to copy, paste, and then format links for use in your blogs, e-mails, or documents? Then see how easy it is to choose a click-and-go format that will save you a lot of time and effort with the CoLT extension for Firef…

vscode配置、使用git

文章目錄一、下載、配置git二、vscode配置并使用git三、記住密碼一、下載、配置git 1、git-win-x64點擊下載后安裝直接安裝&#xff08;建議復制鏈接用迅雷等下載器下載&#xff0c;瀏覽器太慢&#xff0c;記住安裝位置&#xff09;。 2、配置git環境變量&#xff1a; 右鍵 此…

BTrace功能

2019獨角獸企業重金招聘Python工程師標準>>> BTrace功能 一、背景 在生產環境中可能經常遇到各種問題&#xff0c;定位問題需要獲取程序運行時的數據信息&#xff0c;如方法參數、返回值、全局變量、堆棧信息等。為了獲取這些數據信息&#xff0c;我們可以…

.NET(c#) 移動APP開發平臺 - Smobiler(1)

原文&#xff1a;https://www.cnblogs.com/oudi/p/8288617.html 如果說基于.net的移動開發平臺&#xff0c;目前比較流行的可能是xamarin了&#xff0c;不過除了這個&#xff0c;還有一個比xamarin更好用的國內的.net移動開發平臺&#xff0c;smobiler&#xff0c;不用學習另外…

如何在Vizio電視上禁用運動平滑

Vizio維齊奧New Vizio TVs use motion smoothing to make the content you watch appear smoother. This looks good for some content, like sports, but can ruin the feel of movies and TV shows. 新的Vizio電視使用運動平滑來使您觀看的內容顯得更平滑。 這對于某些內容(例…

無服務器架構 - 從使用場景分析其6大特性

2019獨角獸企業重金招聘Python工程師標準>>> 無服務器架構 - 從使用場景分析其6大特性 博客分類&#xff1a; 架構 首先我應該提到&#xff0c;“無服務器”技術肯定有服務器涉及。 我只是使用這個術語來描述這種方法和技術&#xff0c;它將任務處理和調度抽象為與…

ES6實用方法Object.assign、defineProperty、Symbol

文章目錄1.合并對象 - Object.assign()介紹進階注意用途2.定義對象 - Object.defineProperty(obj, prop, descriptor)3.新數據類型- Symbol定義應用1.合并對象 - Object.assign() 介紹 assign方法可以將多個對象&#xff08;字典&#xff09;&#xff0c;語法&#xff1a;Obj…

Enable Authentication on MongoDB

1、Connect to the server using the mongo shell mongo mongodb://localhost:270172、Create the user administrator Change to the admin database: use admindb.createUser({user: "Admin",pwd: "Admin123",roles: [ { role: "userAdminAnyDataba…

windows驅動程序編寫_如何在Windows中回滾驅動程序

windows驅動程序編寫Updating a driver on your PC doesn’t always work out well. Sometimes, they introduce bugs or simply don’t run as well as the version they replaced. Luckily, Windows makes it easy to roll back to a previous driver in Windows 10. Here’s…

運行tomcat報Exception in thread ContainerBackgroundProcessor[StandardEngine[Catalina]]

解決方法1&#xff1a; 手動設置MaxPermSize大小&#xff0c;如果是linux系統&#xff0c;修改TOMCAT_HOME/bin/catalina.sh&#xff0c;如果是windows系統&#xff0c;修改TOMCAT_HOME/bin/catalina.bat&#xff0c; 在“echo "Using CATALINA_BASE: $CATALINA_BASE&q…

new子類會先運行父類的構造函數

發現子類構造函數運行時&#xff0c;先運行了父類的構造函數。為什么呢? 原因&#xff1a;子類的所有構造函數中的第一行&#xff0c;其實都有一條隱身的語句super(); super(): 表示父類的構造函數&#xff0c;并會調用于參數相對應的父類中的構造函數。而super():是在調用父類…

在Windows 7中的Windows Media Player 12中快速預覽歌曲

Do you ever wish you could quickly preview a song without having to play it? Today we look at a quick and easy way to do that in Windows Media Player 12. 您是否曾經希望無需播放就可以快速預覽歌曲&#xff1f; 今天&#xff0c;我們探討一種在Windows Media Play…

Vue.js中的8種組件間的通信方式;3個組件實例是前6種通信的實例,組件直接復制粘貼即可看到運行結果

文章目錄一、$children / $parent二、props / $emit三、eventBus四、ref五、provide / reject六、$attrs / $listeners七、localStorage / sessionStorage八、Vuex實例以element ui為例。例子從上往下逐漸變復雜&#xff08;后面例子沒有刪前面的無用代碼&#xff0c;有時間重新…