Spring Boot2 系列教程 (十八) | 整合 MongoDB


微信公眾號:一個優秀的廢人。如有問題,請后台留言,反正我也不會聽。

廣東清遠

前言

如題,今天介紹下 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();
    }

}

測試結果

MongoDB 增刪改查

Postman 測試已經全部通過,這里僅展示了保存操作。

數據庫結果

這里推薦一個數據庫可視化工具 Robo 3T 。下載地址:https://robomongo.org/download

完整代碼

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

如果覺得對你有幫助,請給個 Star 再走唄,非常感謝。

后語

如果本文對你哪怕有一丁點幫助,請幫忙點好看。你的好看是我堅持寫作的動力。

另外,關注之后在發送 1024 可領取免費學習資料。

資料詳情請看這篇舊文:Python、C++、Java、Linux、Go、前端、算法資料分享


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM