微信公众号:一个优秀的废人。如有问题,请后台留言,反正我也不会听。

前言

如题,今天介绍下 SpringBoot 是如何整合 MongoDB 的。

MongoDB 简介

MongoDB 是由 C++ 编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,它将数据存储为一个文档,数据结构由键值 (key=>value) 对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组,非常灵活。存储结构如下:

{
"studentId": "201311611405",
"age":24,
"gender":"男",
"name":"一个优秀的废人"
}

准备工作

配置数据源

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的更多相关文章

  1. Spring Boot2 系列教程 (十二) | 整合 thymeleaf

    前言 如题,今天介绍 Thymeleaf ,并整合 Thymeleaf 开发一个简陋版的学生信息管理系统. SpringBoot 提供了大量模板引擎,包含 Freemarker.Groovy.Thym ...

  2. Spring Boot2 系列教程 (十六) | 整合 WebSocket 实现广播

    前言 如题,今天介绍的是 SpringBoot 整合 WebSocket 实现广播消息. 什么是 WebSocket ? WebSocket 为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服 ...

  3. Spring Boot2 系列教程(十八)Spring Boot 中自定义 SpringMVC 配置

    用过 Spring Boot 的小伙伴都知道,我们只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好,但是,真实的项目环境比 ...

  4. Spring Boot2 系列教程(十)Spring Boot 整合 Freemarker

    今天来聊聊 Spring Boot 整合 Freemarker. Freemarker 简介 这是一个相当老牌的开源的免费的模版引擎.通过 Freemarker 模版,我们可以将数据渲染成 HTML ...

  5. Spring Boot2 系列教程(十九)Spring Boot 整合 JdbcTemplate

    在 Java 领域,数据持久化有几个常见的方案,有 Spring 自带的 JdbcTemplate .有 MyBatis,还有 JPA,在这些方案中,最简单的就是 Spring 自带的 JdbcTem ...

  6. Spring Boot2 系列教程 (九) | SpringBoot 整合 Mybatis

    前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,本文通过注解的形式实现. 什么是 Mybatis MyBatis 是支持定制化 SQL.存储过程以及 ...

  7. Spring Boot2 系列教程(十六)定时任务的两种实现方式

    在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Qua ...

  8. Spring Boot2 系列教程(十七)SpringBoot 整合 Swagger2

    前后端分离后,维护接口文档基本上是必不可少的工作. 一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了.当然这是一种非常理想的状态,实际开发中却 ...

  9. Spring Boot2 系列教程(二十一)整合 MyBatis

    前面两篇文章和读者聊了 Spring Boot 中最简单的数据持久化方案 JdbcTemplate,JdbcTemplate 虽然简单,但是用的并不多,因为它没有 MyBatis 方便,在 Sprin ...

随机推荐

  1. 下推栈实现(c++编程思想 p136)

    1 头文件Stack.h #ifndef STACK_H #define STACK_H struct Stack { struct Link { void* data; Link* next; vo ...

  2. servicemix-3.2.1 部署异常

    <jbi-task xmlns="http://java.sun.com/xml/ns/jbi/management-message" version="1.0&q ...

  3. 手机web页面调用手机QQ实现在线聊天的效果

    html代码如下: <a href="javascript:;" onclick="chatQQ()">QQ咨询</a> js代码如下: ...

  4. C# 在 8.0 对比 string 和 string? 的类型

    在 C# 8.0 的时候提供了可空字符串的判断,但是可空字符串和字符串的类型是不是不同的? 打开 VisualStudio 2019 这时就不能再使用 VisualStudio 2017 因为不支持 ...

  5. CodeForce - 1187 E. Tree Painting (换根dp)

    You are given a tree (an undirected connected acyclic graph) consisting of nn vertices. You are play ...

  6. 洛谷——P1111修复公路(并查集)

    题目背景 AA地区在地震过后,连接所有村庄的公路都造成了损坏而无法通车.政府派人修复这些公路. 题目描述 给出A地区的村庄数NN,和公路数MM,公路是双向的.并告诉你每条公路的连着哪两个村庄,并告诉你 ...

  7. 精通CSS:高级WEB解决方案

    选择器:高级选择器:属性选择器:[] ,例如:a[href=”#”] {};选择器的优先级:!important为最高优先级,其次优先级次序规则:a,b,c,d ,a代表行内样式,b代表ID选择器,c ...

  8. Libra和中国央行数字货币(DCEP)的对比

    最近偶然和朋友讨论起Libra,对Libra和央行的数字货币方案很感兴趣.梳理了阅读资料(参考见文末)和自己的思考,发知乎留个记录. Libra 是什么? 无国界货币 + 为全球数十亿人服务的金融基础 ...

  9. python3 实现删除数组中相同的元素

    # #把数组中相同的元素去除 # #第一种方式: def del_repeatnum(s=[1,1,1,2,2,3,3,4]): s1=[] for i in s: print(i) if i not ...

  10. 非GUI-Qt程序运行后显示Console(简单好用:在pro文件中加入: CONFIG += console)

    ----我的生活,我的点点滴滴!! 有很多时候,我们在程序中添加了好Debug信息,方便程序在运行期间打印出一些我们需要的信息或者,想用他来显示一些必要信息时, 那么console就太重要了,曾几何时 ...