Springboot連接和操作mongoDB方式
Spring boot是對Spring的進(jìn)一步封裝,旨在簡化Spring的安裝和配置過程。
我們知道使用Spring搭建項目環(huán)境,往往需要引用很多jar包,并隨著業(yè)務(wù)的逐漸復(fù)雜,創(chuàng)建出很多的xml文件。
Spring boot封裝了Spring集成的很多服務(wù)組件,并自動創(chuàng)建這些對象的實例,你只用將所需使用的服務(wù)組件的jar包引入即可快速構(gòu)建開發(fā)環(huán)境。
Spring boot所集成的服務(wù)組件,可在官網(wǎng)找到,你可以勾選所使用的服務(wù)組件,并把相應(yīng)maven 項目下載到本地。
Spring boot同樣集成了對MongoDB等Nosql的支持,下面介紹通過Spring boot連接和操作MongoDB。
創(chuàng)建Spring boot項目
本文使用的IDE是idea,其Spring initializr是創(chuàng)建Spring Boot項目的快速可視化組件,當(dāng)然你也可以構(gòu)建maven項目,然后在Spring boot官網(wǎng)將相關(guān)pom引入。
新建Spring boot項目,輸入spring boot組件自動配置網(wǎng)址,點(diǎn)擊next。
輸入maven項目的的相關(guān)信息,并選擇jdk版本。
選擇需要的服務(wù)組件。
創(chuàng)建出的Spring boot的項目是個空的maven項目,pom內(nèi)包含需要的jar包。
Spring boot連接mongoDB
Spring data提供了操作多種數(shù)據(jù)庫的支持,其api簡潔,調(diào)用方便。我們使用Spring data進(jìn)行MongoDB連接。
在此介紹兩種連接mongodb的方式。
Spring boot有意簡化甚至消除原生Spring框架的xml配置,所以spring boot項目推崇盡量不使用xml配置文件進(jìn)行bean的管理。
第一種方式是使用properties進(jìn)行mongoDB的連接配置
在application.properties中進(jìn)行mongoDB連接字符串配置,org.springframework.boot.autoconfigure.mongo提供了對mongoDB連接字符串的配置支持。我們對指定屬性進(jìn)行配置即可。
注意mongo 2.4以上版本已經(jīng)不支持如下配置了。
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 spring.data.mongodb.username=root spring.data.mongodb.password=root spring.data.mongodb.database=gis
2.4以上版本使用如下連接配置:
spring.data.mongodb.uri=mongodb://root(userName):root(password)@localhost(ip地址):27017(端口號)/gis(collections/數(shù)據(jù)庫)
注意:
如果連接時mongo報錯ASL SCRAM-SHA-1 authentication failed for XXXX on xxx from client xxxx ; UserNotFound: Could not find user xxx 或者java后臺報類似錯誤com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.'
原因有可能是用戶名密碼錯誤,或者需要更改配置通過系統(tǒng)授權(quán)數(shù)據(jù)庫區(qū)進(jìn)行授權(quán)然后再去訪問需要操作的數(shù)據(jù)庫。
添加配置如下:
spring.data.mongodb.database=gis(訪問的目標(biāo)數(shù)據(jù)庫) spring.data.mongodb.authentication-database=admin(mongo自己的管理用戶賬號的數(shù)據(jù)庫)
yml配置文件內(nèi)容如下:
spring: data: mongodb: database: gis authentication-database: admin uri: mongodb://root(userName):root(password)@localhost(ip地址):27017(端口號)
創(chuàng)建數(shù)據(jù)庫操作測試類。
@Component public class DBDaoTest { @Autowired private MongoTemplate mongoTemplate; public void save(Polygon polygon){ mongoTemplate.save(polygon); } public void saveRegions(List<GisRegion> gisRegionList){ mongoTemplate.insert(gisRegionList,GisRegion.class); } public <T> T findById(Class<T> entityClass, String id) { return mongoTemplate.findById(id, entityClass); } public <T> List<T> findAll(Class<T> entityClass) { return mongoTemplate.findAll(entityClass); } public <T> void remove(T entity) { mongoTemplate.remove(entity); } public <T> void add(T entity) { mongoTemplate.insert(entity); } public <T> void addAll(List<T> entity) { mongoTemplate.insertAll(entity); } public <T> void saveOrUpdate(T entity) { mongoTemplate.save(entity); } public <T> T findOne(Class<T> entityClass) { return mongoTemplate.findOne(new Query(), entityClass); } public List<Polygon> findIntersective(GeoJson geoJson){ Query query=new Query(Criteria.where("geometry").intersects(geoJson)); List<Polygon> list=mongoTemplate.find(query,Polygon.class); return list; } public boolean isExistIntersective(GeoJson geoJson){ Query query=new Query(Criteria.where("geometry").intersects(geoJson).and("_id").is(100000)); boolean res=mongoTemplate.exists(query,GisRegion.class); return res; } }
org.springframework.data.mongodb.core包的MongoTemplate類提供對mongodb的所有操作方法,并且會自動裝配連接數(shù)據(jù)庫的MongoDbFactory類對象,我們在application.properties中定義了MongoDbFactory對象所需要的參數(shù),Spring boot會自動幫我們創(chuàng)建該對象供MongoTemplate使用,如果我們沒有指定連接字符串,Spring boot在@Autowired自動裝配MongoTemplate對象時,會默認(rèn)使用127.0.0.1:27017地址、test數(shù)據(jù)庫和無密碼訪問方式。
更多數(shù)據(jù)庫操作方式,請查看MongoTemplate類的具體內(nèi)容。
第二種方式是創(chuàng)建配置類進(jìn)行mongoDB的連接配置
在maven resource文件夾下新建database.properties文件,定義數(shù)據(jù)庫連接字符串。
mongodb.uri=127.0.0.1:27017 mongodb.username=root mongodb.password=root mongodb.schema=gis
考慮在項目實際開發(fā)過程中經(jīng)常會切換環(huán)境,所以可以采用引用外部配置參數(shù)的辦法,Spring boot在propertis文件中使用@…@占位符指定外部參數(shù)。
在pom文件profile中定義外部參數(shù),供propertis文件引用。
pom.xml的profile文件配置如下:
<project> ... <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <db.mongo.server>127.0.0.1:27017</db.mongo.server> <db.mongo.schema>gis</db.mongo.schema> <db.mongo.user>root</db.mongo.user> <db.mongo.password>root</db.mongo.password> </properties> </profile> </profiles> </project>
database.properties文件:
#mongodb.uri=@db.mongo.server@ #mongodb.username=@db.mongo.user@ #mongodb.password=@db.mongo.password@ #mongodb.schema=@db.mongo.schema@
創(chuàng)建MongoDBConfig類,實例化MongoDbFactory bean:
@Configuration //等價于XML中配置bean @PropertySource(value = "classpath:database.properties",ignoreResourceNotFound = true) public class MongoDBConfig { @Value("${mongodb.schema}") private String databaseName; @Value("${mongodb.uri}") private String uri; @Value("${mongodb.username}") private String userName; @Value("${mongodb.password}") private String password; @Bean public MongoDbFactory mongoDbFactory() throws UnknownHostException { String uriStr="mongodb://"+userName+":"+password+"@"+uri+"/"+databaseName; System.out.println(uriStr); MongoClientURI mongoClientURI=new MongoClientURI(uriStr); MongoDbFactory mongoDbFactory=new SimpleMongoDbFactory(mongoClientURI); return mongoDbFactory; } }
Spring框架會在@Autowired自動裝配MongoTemplate時,使用該MongoDbFactory bean。
spring boot操作mongo時添加日志查看mongodb執(zhí)行語句
spring boot通過spring data項目與mongo的交互,提供了很多函數(shù)封裝,方便用戶執(zhí)行操作,故不需再去寫很多原生js代碼段操作mongo。
由于進(jìn)行封裝,導(dǎo)致我們無法在mongo的執(zhí)行日志下看到轉(zhuǎn)義的js執(zhí)行語句,導(dǎo)致復(fù)雜的查詢無法對語句的性能和執(zhí)行細(xì)節(jié)進(jìn)行分析,對于不熟悉spring data api的用戶,編寫的交互代碼往往會浪費(fèi)性能甚至無法得到正確結(jié)果。對此在程序執(zhí)行時,添加日志詳情是必要的。
spring boot自身集成了logback的日志支持,只需在相應(yīng)properties或yml進(jìn)行配置即可。開啟spring data操作mongo的日志支持,
yml示例如下:
logging: level: org.springframework.data.mongodb.core: DEBUG
properties示例如下:
logging.level.org.springframework.data.mongodb.core = DEBUG
可看到執(zhí)行mongo操作時日志詳情示例
如下所示:
2019-07-08 19:46:56.663 INFO 32616 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-2, groupId=group1] Discovered group coordinator 172.28.15.45:9092 (id: 2147483647 rack: null)
2019-07-08 19:46:56.665 INFO 32616 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator : [Consumer clientId=consumer-2, groupId=group1] Revoking previously assigned partitions []
2019-07-08 19:46:56.666 INFO 32616 --- [ntainer#0-0-C-1] o.s.k.l.KafkaMessageListenerContainer : partitions revoked: []
2019-07-08 19:46:56.666 INFO 32616 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-2, groupId=group1] (Re-)joining group
2019-07-08 19:46:56.668 DEBUG 32616 --- [ main] o.s.data.mongodb.core.MongoTemplate : Executing aggregation: [ { "$match" : { "$or" : [ { "type" : ""} , { "type" : null }]}} , { "$group" : { "_id" : "$_id" , "count" : { "$sum" : 1}}} , { "$group" : { "_id" : "$count" , "sum" : { "$sum" : "$count"}}}] in collection osgiSample
2019-07-08 19:46:56.691 INFO 32616 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-2, groupId=group1] Successfully joined group with generation 143
2019-07-08 19:46:56.692 INFO 32616 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator : [Consumer clientId=consumer-2, groupId=group1] Setting newly assigned partitions [group1Topic-0]
2019-07-08 19:46:56.700 INFO 32616 --- [ntainer#0-0-C-1] o.s.k.l.KafkaMessageListenerContainer : partitions assigned: [group1Topic-0]
2019-07-08 19:46:56.774 INFO 32616 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:24498}] to 172.28.13.215:20036
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot3.4.0無法找到StringRedisTemplate?bean的問題Consider?def
本文主要介紹了SpringBoot3.4.0無法找到StringRedisTemplate?bean的問題Consider?defining?a?bean?of?type?‘org.springframework,具有一定的參考價值,感興趣的可以了解一下2025-03-03@Autowired與@Resource在實現(xiàn)對象注入時的區(qū)別
這篇文章主要介紹了@Autowired與@Resource在實現(xiàn)對象注入時的區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-04-04Spring IOC源碼剖析_如何整體認(rèn)知Spring體系結(jié)構(gòu)
這篇文章主要介紹了Spring IOC源碼剖析_如何整體認(rèn)知Spring體系結(jié)構(gòu)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09sentinel整合ribbon與fallback流程分步講解
這篇文章主要介紹了sentinel整合ribbon與fallback分步流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Java ApiPost請求返回406狀態(tài)碼問題的解決方案
APIPost是一款專為開發(fā)者和測試人員設(shè)計的API測試工具,類似于Postman,但提供了更多的團(tuán)隊協(xié)作和文檔管理功能,它可以幫助你更好地進(jìn)行接口調(diào)試和集成測試,但遇到了請求后返回的是406狀態(tài),所以本文給大家介紹了Java ApiPost請求返回406狀態(tài)碼問題的解決方案2025-04-04