目录
本文环境:Java JDK 8 + Spring Boot 2.3.5 + mongodb-windows-7.0.12。
官网文档:spring-boot/docs/2.3.5.RELEASE/#boot-features-mongodb。
Spring Data 下的模块都是类似的,与操作 redis、jpa 等完全差不多,所以操作 MongoDB 也很简单。
MongoDB 快速使用入门
引入数据库驱动依赖
1、Spring Data 即提供了统一的 Repository(仓库) 接口,又提供了数据访问模板类 xxxTemplate,如:MongoTemplate、RedisTemplate 等。可参考:Spring Data 简介。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
pom.xml · 汪少棠/web_app - Gitee.com。
全局属性配置
spring:
data:
# 配置 MongoDB 连接
mongodb:
# 连接地址,wmx 相当于是数据库名称,不存在时会自动新建
uri: mongodb://localhost:27017/wmx
src/main/resources/application.yml · 汪少棠/web_app - Gitee.com。
1、Spring boot 官网完整的配置属性如下:
属性 | 默认值 | 描述 |
---|---|---|
| Authentication database name. | |
| Whether to enable auto-index creation. | |
| Database name. | |
| Fully qualified name of the FieldNamingStrategy to use. | |
| GridFS database name. | |
| Mongo server host. Cannot be set with URI. | |
| Login password of the mongo server. Cannot be set with URI. | |
| Mongo server port. Cannot be set with URI. | |
| Required replica set name for the cluster. Cannot be set with URI. | |
|
| Type of Mongo repositories to enable. |
|
| Mongo database URI. Cannot be set with host, port, credentials and replica set name. |
| Login user of the mongo server. Cannot be set with URI. | |
|
| Representation to use when converting a UUID to a BSON binary value. |
MongoDB 基本增删改查
1、两种操作方式:
a)自定义持久层接口继承 org.springframework.data.mongodb.repository.MongoRepository 接口。
b)直接使用 org.springframework.data.mongodb.core.MongoTemplate 模板。
2、具体可参考下面的演示代码:
src/main/java/com/wmx/web_app/mongodb/pojo/Person.java · 汪少棠/web_app - Gitee.com。
src/main/java/com/wmx/web_app/mongodb/dao/PersonRepository.java · 汪少棠/web_app - Gitee.com。
src/main/java/com/wmx/web_app/mongodb/controller/PersonController.java · 汪少棠/web_app - Gitee.com。