Spring Boot2 系列教程 (十八) | 整合 MongoDB
微信公众号:一个优秀的废人。如有问题,请后台留言,反正我也不会听。

前言
如题,今天介绍下 SpringBoot 是如何整合 MongoDB 的。
MongoDB 简介
MongoDB 是由 C++ 编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,它将数据存储为一个文档,数据结构由键值 (key=>value) 对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组,非常灵活。存储结构如下:
{
"studentId": "201311611405",
"age":24,
"gender":"男",
"name":"一个优秀的废人"
}
准备工作
- SpringBoot 2.1.3 RELEASE
- MongnDB 2.1.3 RELEASE
- MongoDB 4.0
- IDEA
- JDK8
- 创建一个名为 test 的数据库,不会建的。参考菜鸟教程:
http://www.runoob.com/mongodb/mongodb-tutorial.html
配置数据源
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
以上是无密码写法,如果 MongoDB 设置了密码应这样设置:
spring:
data:
mongodb:
uri: mongodb://name:password@localhost:27017/test
pom 依赖配置
<!-- mongodb 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- test 依赖(没用到) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
实体类
@Data
public class Student {
@Id
private String id;
@NotNull
private String studentId;
private Integer age;
private String name;
private String gender;
}
dao 层
和 JPA 一样,SpringBoot 同样为开发者准备了一套 Repository ,只需要继承 MongoRepository 传入实体类型以及主键类型即可。
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
service 层
public interface StudentService {
Student addStudent(Student student);
void deleteStudent(String id);
Student updateStudent(Student student);
Student findStudentById(String id);
List<Student> findAllStudent();
}
实现类:
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
/**
* 添加学生信息
* @param student
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Student addStudent(Student student) {
return studentRepository.save(student);
}
/**
* 根据 id 删除学生信息
* @param id
*/
@Override
public void deleteStudent(String id) {
studentRepository.deleteById(id);
}
/**
* 更新学生信息
* @param student
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Student updateStudent(Student student) {
Student oldStudent = this.findStudentById(student.getId());
if (oldStudent != null){
oldStudent.setStudentId(student.getStudentId());
oldStudent.setAge(student.getAge());
oldStudent.setName(student.getName());
oldStudent.setGender(student.getGender());
return studentRepository.save(oldStudent);
} else {
return null;
}
}
/**
* 根据 id 查询学生信息
* @param id
* @return
*/
@Override
public Student findStudentById(String id) {
return studentRepository.findById(id).get();
}
/**
* 查询学生信息列表
* @return
*/
@Override
public List<Student> findAllStudent() {
return studentRepository.findAll();
}
}
controller 层
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/add")
public Student addStudent(@RequestBody Student student){
return studentService.addStudent(student);
}
@PutMapping("/update")
public Student updateStudent(@RequestBody Student student){
return studentService.updateStudent(student);
}
@GetMapping("/{id}")
public Student findStudentById(@PathVariable("id") String id){
return studentService.findStudentById(id);
}
@DeleteMapping("/{id}")
public void deleteStudentById(@PathVariable("id") String id){
studentService.deleteStudent(id);
}
@GetMapping("/list")
public List<Student> findAllStudent(){
return studentService.findAllStudent();
}
}
测试结果

Postman 测试已经全部通过,这里仅展示了保存操作。

这里推荐一个数据库可视化工具 Robo 3T 。下载地址:https://robomongo.org/download
完整代码
https://github.com/turoDog/Demo/tree/master/springboot_mongodb_demo
如果觉得对你有帮助,请给个 Star 再走呗,非常感谢。
后语
如果本文对你哪怕有一丁点帮助,请帮忙点好看。你的好看是我坚持写作的动力。
另外,关注之后在发送 1024 可领取免费学习资料。
资料详情请看这篇旧文:Python、C++、Java、Linux、Go、前端、算法资料分享
Spring Boot2 系列教程 (十八) | 整合 MongoDB的更多相关文章
- Spring Boot2 系列教程 (十二) | 整合 thymeleaf
前言 如题,今天介绍 Thymeleaf ,并整合 Thymeleaf 开发一个简陋版的学生信息管理系统. SpringBoot 提供了大量模板引擎,包含 Freemarker.Groovy.Thym ...
- Spring Boot2 系列教程 (十六) | 整合 WebSocket 实现广播
前言 如题,今天介绍的是 SpringBoot 整合 WebSocket 实现广播消息. 什么是 WebSocket ? WebSocket 为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服 ...
- Spring Boot2 系列教程(十八)Spring Boot 中自定义 SpringMVC 配置
用过 Spring Boot 的小伙伴都知道,我们只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好,但是,真实的项目环境比 ...
- Spring Boot2 系列教程(十)Spring Boot 整合 Freemarker
今天来聊聊 Spring Boot 整合 Freemarker. Freemarker 简介 这是一个相当老牌的开源的免费的模版引擎.通过 Freemarker 模版,我们可以将数据渲染成 HTML ...
- Spring Boot2 系列教程(十九)Spring Boot 整合 JdbcTemplate
在 Java 领域,数据持久化有几个常见的方案,有 Spring 自带的 JdbcTemplate .有 MyBatis,还有 JPA,在这些方案中,最简单的就是 Spring 自带的 JdbcTem ...
- Spring Boot2 系列教程 (九) | SpringBoot 整合 Mybatis
前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,本文通过注解的形式实现. 什么是 Mybatis MyBatis 是支持定制化 SQL.存储过程以及 ...
- Spring Boot2 系列教程(十六)定时任务的两种实现方式
在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Qua ...
- Spring Boot2 系列教程(十七)SpringBoot 整合 Swagger2
前后端分离后,维护接口文档基本上是必不可少的工作. 一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了.当然这是一种非常理想的状态,实际开发中却 ...
- Spring Boot2 系列教程(二十一)整合 MyBatis
前面两篇文章和读者聊了 Spring Boot 中最简单的数据持久化方案 JdbcTemplate,JdbcTemplate 虽然简单,但是用的并不多,因为它没有 MyBatis 方便,在 Sprin ...
随机推荐
- Java集合系统
前言: 要想学习java的集合体系,就必须先了解java的集合框架,总的来说,分为Collection和Map体系. Collection集合框架: Map集合框架: 一. Collection接口 ...
- H3C HDLC帧格式
- H3C 以跳数评估的路由并非最优路径
- BZOJ 4236 "JOIOJI"(前缀和+map+pair)
传送门: [1]:BZOJ [2]:洛谷 •题解 定义数组 a,b,c 分别表示 'J' , 'O' , 'I' 的前缀和: 要想使区间 (L,R] 满足条件当且仅当 a[R]-a[L] = b[R] ...
- 【js】 vue 2.5.1 源码学习(六) initProxy initLifeCycle 渲染函数的作用域代理
大体思路 (五) 1. initProxy 渲染函数的作用域代理 ==> es6 如果支持proxy (hasProxy) 就用proxy 不支持就用 defineProperty() prox ...
- Postman:非专业的并发测试
Postman是开发中常用的接口测试工具,也可以用来进行并发测试. 使用方法如下: 1. 直接输入url 选择GET方法,点击Send. 结果打印一个"test",如下: 2. 使 ...
- shell 脚本文件十六进制转化为ascii码代码, Shell中ASCII值和字符之间的转换
Shell中ASCII值和字符之间的转换 1.ASCII值转换为字符 方法一: i=97 echo $i | awk '{printf("%c", $1)}' ...
- You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
异常 You are using the runtime-only build of Vue where the template compiler is not available. Either ...
- web.config修改文件修改上传大小
老是要修改上传文件大小的限制,先记在这里. <httpRuntime maxRequestLength= "1048576 " //最大长度 executionTimeout ...
- MYSQL基本常用函数
MYSQL基本常用函数 一.字符的操作函数 (ps:mysql中的索引都是从1开始的.) 1.instr(param1,param2) 返回子串第一次出现的索引,若找不到则返回0. param1填写操 ...