来源:素文宅博客
地址: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,参考如图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/a38529e68dac21fcbcf667232a54a237.png)
2、下载mongodb-win32-x86_64-2012plus-4.2.5.zip文件压缩包为例,解压文件后目录如下:
![](https://i-blog.csdnimg.cn/blog_migrate/a5469262e79a575abea15ef8d0315a34.png)
3、启动MongoDB服务
1)使用cmd命令切换目录,执行命令如下:
1 | cmd E:\tools\mongodb-win32-x86_64-2012plus-4.2.5\mongodb-win32-x86_64-2012plus-4.2.5\bin |
2)启动MongoDB服务,执行命令如下:
1 | mongod --dbpath E:\software\MongoDB\data |
![](https://i-blog.csdnimg.cn/blog_migrate/f94dd6e4589a1e9d2a44ba55ac35efcd.png)
![](https://i-blog.csdnimg.cn/blog_migrate/52614823052d6cb65e2dfaf030dabfe0.png)
4、查看启动情况
在浏览器输入http://localhost:27017 (27017是mongodb的端口号)查看,若显示:
![](https://i-blog.csdnimg.cn/blog_migrate/1b17a9b61169d5b264d021d4deb49593.png)
则表示连接成功,反之不成功,可以查看端口是否被占用。
配置及实体类文件
1、pom.xml文件
在pom.xml文件中加入spring-boot-starter-data-mongodb引入对mongodb的访问支持依赖,它的实现依赖spring-data-mongodb,配置信息如下:
1 2 3 4 | <dependency> <groupId>org.springframework.boot< /groupId > <artifactId>spring-boot-starter-data-mongodb< /artifactId > < /dependency > |
本项目案例中pom.xml文件配置信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?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文件中增加内容如下:
1 2 3 | # mongodb 配置 spring.data.mongodb.uri=mongodb: //localhost :27017 spring.data.mongodb.database=selection |
3、编写BootUser实体对象
BootUser类文件对应MongoDB数据库表的字段属性值,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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接口,具体代码如下:
1 2 3 4 5 6 7 8 | 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接口类文件,具体代码如下:
1 2 3 4 5 6 7 | 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文件,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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类文件,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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数据库,如图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/721a082110430e771886fb6c17bfe77c.png)
方式二:使用MongoTemplate
1、Spring Boot会自动注入mongotemplate,此方式比较简单直接,在之前新建的HelloWorldController类文件,增加代码内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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系列文章也在持续更新中,大家可以收藏便于后面浏览学习参考。下面大家有时间的话可以试一试,有什么疑问欢迎下方留言。