來源:素文宅博客
地址:https://blog.yoodb.com/yoodb/article/detail/1578
MongoDB是一個開源的NoSQL文檔數據庫。它可以存儲多種數據結構,類似JSON的BSON,可以存儲複雜數據類型。
Spring Boot爲使用MongoDB提供了很多便利,包括spring-boot-starter-data-mongodb 'Starter POM'。本文學習一下Spring Boot中整合MongoDB數據庫,來實現以不同方法讀寫MongoDB數據庫,分別是新建接口類實現MongoRepository接口和直接使用MongoTemplate類兩種方法。
MongoDB最大的特點是支持的查詢語言非常強大,其語法類似面向對象的方式,可以實現類似關係數據庫單表查詢的絕大部分功能,而且還支持對數據建立索引。
MongoDB下載安裝及啓動
1、MongoDB下載https://www.mongodb.com/download-center/community?jmp=docs
參考如圖所示:
2、下載mongodb-win32-x86_64-2012plus-4.2.5.zip文件壓縮包爲例,解壓文件後目錄如下:
3、啓動MongoDB服務1)使用cmd命令切換目錄,執行命令如下:
cmd E:\tools\mongodb-win32-x86_64-2012plus-4.2.5\mongodb-win32-x86_64-2012plus-4.2.5\bin
2)啓動MongoDB服務,執行命令如下:
mongod --dbpath E:\software\MongoDB\data
4、查看啓動情況
在瀏覽器輸入http://localhost:27017 (27017是mongodb的端口號)查看,若顯示:
則表示連接成功,反之不成功,可以查看端口是否被佔用。
配置及實體類文件
1、pom.xml文件
在pom.xml文件中加入spring-boot-starter-data-mongodb引入對mongodb的訪問支持依賴,它的實現依賴spring-data-mongodb,配置信息如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
本項目案例中pom.xml文件配置信息如下:
<?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 https://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.2.5.RELEASE</version> <relativePath/> </parent> <groupId>com.yoodb.study.demo06</groupId> <artifactId>springboot-study-demo06</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>springboot-study-demo06</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2、數據源配置
在application.properties文件中增加內容如下:
# mongodb 配置 spring.data.mongodb.uri=mongodb://localhost:27017 spring.data.mongodb.database=selection
3、編寫BootUser實體對象
BootUser類文件對應MongoDB數據庫表的字段屬性值,具體代碼如下:
package com.yoodb.study.demo06.entity; import java.io.Serializable; public class BootUser implements Serializable { private String id; private String name; private String detail; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } }
MongoDB讀寫方式
方式一:MongoRepository接口1、定義UserRepository接口類文件新建repository接口並繼承MongoRepository接口,具體代碼如下:
package com.yoodb.study.demo06.repository; import com.yoodb.study.demo06.entity.BootUser; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Service; @Service public interface UserRepository extends MongoRepository<BootUser, String> { public BootUser save(BootUser user); }
注意:定義接口繼承MongoRepository類,在Spring Boot框架中若查詢一些數據,只需要按照格式寫一個接口名和對應的參數即可。
2、定義UserService接口類文件,具體代碼如下:
package com.yoodb.study.demo06.service; import com.yoodb.study.demo06.entity.BootUser; import org.springframework.stereotype.Repository; @Repository public interface UserService { public void save(BootUser user); }
3、新建UserService接口類的實現類UserServiceImpl文件,具體代碼如下:
package com.yoodb.study.demo06.service.impl; import com.yoodb.study.demo06.entity.BootUser; import com.yoodb.study.demo06.repository.UserRepository; import com.yoodb.study.demo06.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; public void save(BootUser user) { userRepository.save(user); } }
4、新建HelloWorldController類文件,具體代碼如下:
package com.yoodb.study.demo06; import com.yoodb.study.demo06.entity.BootUser; import com.yoodb.study.demo06.service.UserService; 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.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { @Autowired private UserService userService; @RequestMapping("save") public boolean save(){ // 插入數據 BootUser user = new BootUser(); user.setId("003"); user.setName("素文宅博客"); user.setDetail("003關注“Java精選”微信公衆號,一起進步!"); mongotemplate.save(user); return true; } }
5、啓動項目訪問地址如下:
http://localhost:8080/save
返回結果如下:
true
數據已存儲到MongoDB數據庫,如圖所示:
方式二:使用MongoTemplate
1、Spring Boot會自動注入mongotemplate,此方式比較簡單直接,在之前新建的HelloWorldController類文件,增加代碼內容如下:
package com.yoodb.study.demo06; import com.yoodb.study.demo06.entity.BootUser; import com.yoodb.study.demo06.service.UserService; 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.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { @Autowired private UserService userService; @Autowired private MongoTemplate mongotemplate; @RequestMapping("save") public boolean save(){ // 插入數據 BootUser user = new BootUser(); user.setId("003"); user.setName("素文宅博客"); user.setDetail("003關注“Java精選”微信公衆號,一起進步!"); mongotemplate.save(user); return true; } @RequestMapping("select") public String select(String id){ //查詢數據 Query query = new Query(); query.addCriteria(Criteria.where("id").is(id)); String detail = mongotemplate.findOne(query, BootUser.class).getDetail(); return detail; } }
2、啓動項目
訪問地址如下:
http://localhost:8080/select?id=001
返回結果如下:
001關注“Java精選”微信公衆號,一起進步!
本文篇文章的項目源碼(springboot-study-demo06)地址:
https://github.com/yoodb/springboot
到此,關於Spring boot整合MongoDB實現讀寫非關係型數據庫的兩種方式就講完了,後續Spring Cloud系列文章也在持續更新中,大家可以收藏便於後面瀏覽學習參考。下面大家有時間的話可以試一試,有什麼疑問歡迎下方留言。