SpringBoot 實戰 (十八) | 整合 MongoDB

微信公衆號:一個優秀的廢人。若有問題,請後臺留言,反正我也不會聽。html

廣東清遠

前言

如題,今天介紹下 SpringBoot 是如何整合 MongoDB 的。前端

MongoDB 簡介

MongoDB 是由 C++ 編寫的非關係型數據庫,是一個基於分佈式文件存儲的開源數據庫系統,它將數據存儲爲一個文檔,數據結構由鍵值 (key=>value) 對組成。MongoDB 文檔相似於 JSON 對象。字段值能夠包含其餘文檔,數組及文檔數組,很是靈活。存儲結構以下:java

{
	"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 設置了密碼應這樣設置:git

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 傳入實體類型以及主鍵類型便可。github

@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();

}
複製代碼

實現類:web

@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/downloadspring

完整代碼

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

若是以爲對你有幫助,請給個 Star 再走唄,很是感謝。數據庫

後語

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

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

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

一個優秀的廢人,給你講幾斤技術
相關文章
相關標籤/搜索