关键词:
微信公众号:一个优秀的废人。如有问题,请后台留言,反正我也不会听。
前言
如题,今天介绍下 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、前端、算法资料分享
springboot2系列教程|springboot整合mybatis
前言如题,今天介绍SpringBoot与Mybatis的整合以及Mybatis的使用,本文通过注解的形式实现。什么是MybatisMyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取... 查看详情
springboot2系列教程(十六)|整合websocket实现广播
前言如题,今天介绍的是SpringBoot整合WebSocket实现广播消息。什么是WebSocket?WebSocket为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服务器发送信息,反之也成立。WebSocket是通过一个socket来实现双工异步通信能力... 查看详情
springboot2系列教程|整合数据缓存cache
如题,今天介绍SpringBoot的数据缓存。做过开发的都知道程序的瓶颈在于数据库,我们也知道内存的速度是大大快于硬盘的,当需要重复获取相同数据时,一次又一次的请求数据库或者远程服务,导致大量时间耗费在数据库查询... 查看详情
springboot2系列教程(十七)|整合websocket实现聊天室
微信公众号:一个优秀的废人。如有问题,请后台留言,反正我也不会听。前言昨天那篇介绍了WebSocket实现广播,也即服务器端有消息时,将消息发送给所有连接了当前endpoint的浏览器。但这无法解决消息由谁发送,又由谁接收... 查看详情
十八springboot2核心技术——整合redis(代码片段)
SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情
十八springboot2核心技术——整合redis(代码片段)
SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情
springboot应用系列5--springboot2整合logback
上一篇我们梳理了SpringBoot2整合log4j2的配置过程,其中讲到了SpringBoot2原装适配logback,并且在非异步环境下logback和log4j2的性能差别不大,所以对于那些日志量不算太高的项目来说,选择logback更简单方便。1.pom.xmlpom.xml不需要添加... 查看详情
springboot应用系列6--springboot2整合quartz
Quartz是实现定时任务的利器,Quartz主要有四个组成部分,分别是:1.Job(任务):包含具体的任务逻辑;2.JobDetail(任务详情):是对Job的一种详情描述;3. Trigger(触发器):负责管理触发JobDetail的机制;4. Scheduler(调度器):负... 查看详情
springboot2.0整合同时支持jsp+html跳转(代码片段)
springboot项目创建教程 https://blog.csdn.net/q18771811872/article/details/88126835springboot2.0跳转html教程 https://blog.csdn.net/q18771811872/article/details/88312862springboot2.0跳转jsp教程 https:/ 查看详情
comicenhancerpro系列教程十八:jpg文件长度与质量
作者:马健邮箱:[email protected] 主页:http://www.comicer.com/stronghorse/ 发布:2017.07.23教程十八:JPG文件长度与质量 众所周知,JPG是一种“有损”压缩格式,与PNG等无损压缩格式相比,最大的问题是:如果反复压缩,会造成图像... 查看详情
springboot应用系列4--springboot2整合log4j2
一、背景1.log4j2传承于log4j和logback,它是目前性能最好的日志处理工具,有关它们的性能对比请看:2.除了性能好之外,log4j2有这么几个重要的新features:(1)自动热重载配置文件,而且重新加载期间不会丢失日志请求。logback也可以... 查看详情
springboot2系列教程|配置日志
前言如题,今天介绍springboot默认日志的配置。默认日志Logback默认情况下,SpringBoot用Logback来记录日志,并用INFO级别输出到控制台。如果你在平常项目中用过SpringBoot,你应该已经注意到很多INFO级别的日志了。默认日志长这样:20... 查看详情
springboot2系列教程(十四)|统一异常处理
如题,今天介绍SpringBoot是如何统一处理全局异常的。SpringBoot中的全局异常处理主要起作用的两个注解是@ControllerAdvice和@ExceptionHandler,其中@ControllerAdvice是组件注解,添加了这个注解的类能够拦截Controller的请求,而ExceptionHandler... 查看详情
springboot2系列教程|使用jdbctemplates访问mysql
...dbc访问关系型mysql,通过spring的JdbcTemplate去访问。准备工作SpringBoot2.xjdk1.8maven3.0ideamysql构建SpringBoot项目,不会的朋友参考旧文章:如何使用IDEA构建SpringBoot工程项目目录结构pom文件引入依赖<dependencies><!--jdbcTempl 查看详情
wpf入门教程系列十八——wpf中的数据绑定
六、排序 如果想以特定的方式对数据进行排序,可以绑定到CollectionViewSource,而不是直接绑定到ObjectDataProvider。CollectionViewSource则会成为数据源,并充当截取ObjectDataProvider中的数据的媒介,并提供排序、分组和... 查看详情
springboot2系列教程|实现声明式事务
前言如题,今天介绍SpringBoot的声明式事务。Spring的事务机制所有的数据访问技术都有事务处理机制,这些技术提供了API用于开启事务、提交事务来完成数据操作,或者在发生错误时回滚数据。而Spring的事务机制是用统一的机制... 查看详情
springboot2.x基础教程:springboot整合mybatis附源码(代码片段)
微信号:hzy1014211086,如果你正在学习SpringBoot,可以加入我们的Spring技术交流群,共同成长文章目录一、准备数据表二、添加依赖三、配置数据源四、编写领域对象五、注解配置方式新增修改查询删除六、XML配置... 查看详情
springboot2系列教程理解springboot配置文件application.properties
在SpringBoot中,配置文件有两种不同的格式,一个是properties,另一个是yaml。虽然properties文件比较常见,但是相对于properties而言,yaml更加简洁明了,而且使用的场景也更多,很多开源项目都是使用yaml进行配置(例如Hexo)。除了... 查看详情