Spring Boot之使用MongoDB数据库源
前言
来啦老铁!
笔者学习Spring Boot有一段时间了,附上Spring Boot系列学习文章,欢迎取阅、赐教:
- 5分钟入手Spring Boot;
- Spring Boot数据库交互之Spring Data JPA;
- Spring Boot数据库交互之Mybatis;
- Spring Boot视图技术;
- Spring Boot之整合Swagger;
- Spring Boot之junit单元测试踩坑;
- 如何在Spring Boot中使用TestNG;
- Spring Boot之整合logback日志;
- Spring Boot之整合Spring Batch:批处理与任务调度;
- Spring Boot之整合Spring Security: 访问认证;
- Spring Boot之整合Spring Security: 授权管理;
- Spring Boot之多数据库源:极简方案;
在上一篇文章Spring Boot之多数据库源:极简方案中,我们已经能在Spring Boot项目中使用Oracle、Mysql等数据库源,并在文末留了一个悬念:
-
如何在Spring Boot项目中使用MongoDB数据库源?
今天,他来了!
项目代码仍用已上传的Git Hub仓库,欢迎取阅:
整体步骤
- 添加MongoDB项目依赖;
- 添加MongoDB数据库信息;
- 实现MongoDB交互过程;
- 验证MongoDB交互效果;
1. 添加MongoDB项目依赖;
在项目pom.xml文件中添加MongoDB依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
注意,spring-boot-starter-data-mongodb是Spring Boot默认支持的,不需要带上版本号,默认与spring-boot-starter-parent是同一版本;
记得安装一下依赖:
mvn install -Dmaven.test.skip=true -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true
2. 添加MongoDB数据库信息;
在application.properties中声明MongoDB的数据库信息即可,换句话说,就是要告诉Spring Boot,我们数据库的用户名、密码、数据库位置、端口等信息,如:
#configuration for mongo
spring.data.mongodb.uri=mongodb://username:password@127.0.0.1:27017/database?ssl=true
稍微说明一下:
- username:目标数据库的用户名,请依实际情况填写;
- password:目标数据库的密码,请依实际情况填写;
- 127.0.0.1:目标数据库host,请依实际情况填写;
- 27017:目标数据库端口,请依实际情况填写;
- database:目标数据库名称,请依实际情况填写;
- ssl=true:交互时采用ssl协议,请依实际情况使用;
对应到MongoDB客户端工具,如Robotmongo:



3. 实现MongoDB交互过程;
在实现交互过程之前,我先介绍一下我手上的数据库,由于使用了公司的测试数据库,不方便公开,因此进行了局部遮挡:

- 我使用数据库表agent_config进行演示;
- agent_config表共有2个根节点:_id和application,_id为唯一标识,application为具体业务信息;
接下来我们来实现交互过程:
1). 创建AgentConfig实体类;
在domain包下创建AgentConfig实体类:
package com.github.dylanz666.domain;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
/**
* @author : dylanz
* @since : 09/19/2020
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@Document(collection = "agent_config")
public class AgentConfig implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String _id;
private JSONObject application;
}
注意关键一行代码,这行代码指明了数据库表名为agent_config表;
@Document(collection = "agent_config")
2). 创建repository包,用于存放MongoDB交互的接口;
3). 在repository包内创建AgentConfigRepository类;
package com.github.dylanz666.repository;
import com.github.dylanz666.domain.AgentConfig;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* @author : dylanz
* @since : 09/19/2020
*/
@Repository
public interface AgentConfigRepository {
Optional<AgentConfig> findById(String id);
Optional<AgentConfig> saveAgentConfig(AgentConfig agentConfig);
}
为了演示MongoDB交互过程,我准备开发2个API,一个为获取agent_config表中的数据,一个为更新agent_config中的数据;
4). 在service包下创建AgentConfigService类,编写service;
package com.github.dylanz666.service;
import com.github.dylanz666.domain.AgentConfig;
import com.github.dylanz666.repository.AgentConfigRepository;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* @author : dylanz
* @since : 09/19/2020
*/
@Service
public class AgentConfigService implements AgentConfigRepository {
@Autowired
private MongoTemplate mongoTemplate;
public Optional<AgentConfig> findById(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
return Optional.ofNullable(mongoTemplate.findOne(query, AgentConfig.class));
}
public Optional<AgentConfig> saveAgentConfig(AgentConfig agentConfig) {
String id = agentConfig.get_id();
Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
update.set("application", agentConfig.getApplication());
mongoTemplate.updateFirst(query, update, AgentConfig.class);
return findById(id);
}
}
我们在service内实现了AgentConfigRepository接口,可供controller使用;
5). controller内创建2个演示API;
在controller包内创建AgentConfigController,实现一个使用MongoDB的API:
package com.github.dylanz666.controller;
import com.github.dylanz666.domain.AgentConfig;
import com.github.dylanz666.service.AgentConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
/**
* @author : dylanz
* @since : 09/19/2020
*/
@RestController
public class AgentConfigController {
@Autowired
private AgentConfigService agentConfigService;
@GetMapping("/agent/config/{id}")
@ResponseBody
public Optional<AgentConfig> getAgentConfigById(@PathVariable(name = "id") String id) {
return agentConfigService.findById(id);
}
@PostMapping("/agent/config")
@ResponseBody
public Optional<AgentConfig> save(@RequestBody AgentConfig agentConfig) {
return agentConfigService.saveAgentConfig(agentConfig);
}
}
至此,项目整体结构如下:

4. 验证MongoDB交互效果;
-
启动项目:


-
调用API:
1). 首先在浏览器中直接访问API:http://127.0.0.1:8080/agent/config/5b3e205fd33415007ef7b6f5

2). 使用postman更新MongoDB中的数据:

我们将ddsTimeIntervalCount这个字段的值从1改为2,并且能够在response body中得知,ddsTimeIntervalCount的确有被更新成功!
很明显,我们已经能够如我们预期,正确地访问、修改MongoDB中对应的数据了,事实上,对MongoDB的增删改查已不再有壁垒,我们已经打通MongoDB这条线了!!!
至此,我们的Spring Boot多数据库源从此多了MongoDB支持,Spring Boot多数据库源又上一层楼!!!
如果本文对您有帮助,麻烦点赞+关注!
谢谢!