SpringBoot 实战 (十八) | 整合 MongoDB

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 如题,今天介绍下 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();
    }
}


测试结果

f1f38760acb2310fb0d0e712dde19f6e.jpg


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


b730ac229a89392c6cdb38aa843d8827.png


这里推荐一个数据库可视化工具 Robo 3T 。


下载地址:https://robomongo.org/download


完整代码


https://github.com/turoDog/Demo/tree/master/springboot_mongodb_demo


如果觉得对你有帮助,请给个 Star 再走呗,非常感谢。


后语


如果本文对你哪怕有一丁点帮助,请帮忙点好看。你的好看是我坚持写作的动力。

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
1月前
|
存储 Java Maven
Spring Boot WebFlux 增删改查完整实战 demo
Spring Boot WebFlux 增删改查完整实战 demo
|
8天前
|
监控 Java 微服务
Spring Boot微服务部署与监控的实战指南
【7月更文挑战第19天】Spring Boot微服务的部署与监控是保障应用稳定运行和高效维护的重要环节。通过容器化部署和云平台支持,可以实现微服务的快速部署和弹性伸缩。而利用Actuator、Prometheus、Grafana等监控工具,可以实时获取应用的运行状态和性能指标,及时发现并解决问题。在实际操作中,还需根据应用的具体需求和场景,选择合适的部署和监控方案,以达到最佳效果。
|
22天前
|
NoSQL Java MongoDB
Spring Boot与MongoDB的集成应用
Spring Boot与MongoDB的集成应用
|
1月前
|
存储 NoSQL MongoDB
MongoDB实战面试指南:常见问题一网打尽
MongoDB实战面试指南:常见问题一网打尽
|
29天前
|
Dubbo Java 应用服务中间件
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
Spring Boot 调用 Dubbo 接口与编写 Dubbo 接口实战
66 1
|
18天前
|
存储 NoSQL Java
使用Spring Boot和MongoDB构建NoSQL应用
使用Spring Boot和MongoDB构建NoSQL应用
|
26天前
|
NoSQL Java MongoDB
如何在Spring Boot应用中集成MongoDB数据库
如何在Spring Boot应用中集成MongoDB数据库
|
29天前
|
JSON 安全 Java
Spring Boot与WebFlux的实战案例
Spring Boot与WebFlux的实战案例
|
29天前
|
NoSQL Java MongoDB
如何在Spring Boot应用中集成MongoDB数据库
如何在Spring Boot应用中集成MongoDB数据库
|
1月前
|
NoSQL Java 关系型数据库
非关系型数据库NoSQL数据层解决方案 之 Mongodb 简介 下载安装 springboot整合与读写操作
非关系型数据库NoSQL数据层解决方案 之 Mongodb 简介 下载安装 springboot整合与读写操作
42 0