天天看點

MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB

通過前面四篇的學習,我們已經在本地安裝了一個MongoDB資料庫,并且通過一個簡單的Spring boot應用的單元測試,插入了幾條記錄到MongoDB中,并通過MongoDB Compass檢視到了插入的資料。 MongoDB最簡單的入門教程之一 環境搭建 MongoDB最簡單的入門教程之二 使用nodejs通路MongoDB MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB裡插入資料 MongoDB最簡單的入門教程之四:使用Spring Boot操作MongoDB 本文我們更進一步,通過Spring Boot構造出Restful API,這樣可以直接在浏覽器裡通過調用Restful API對Spring Boot進行增删查改了。

MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
先看效果,假設我本地MongoDB的資料庫裡有一張表book,隻有一條記錄,id為1。
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
通過浏覽器裡的這個url根據id讀取該記錄: http://localhost:8089/bookmanage/read?id=1
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
記錄的建立: http://localhost:8089/bookmanage/create?id=2&name=Spring&author=Jerry
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
記錄的搜尋: http://localhost:8089/bookmanage/search?name= *
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
記錄的删除:删除id為2的記錄 http://localhost:8089/bookmanage/delete?id=2

下面是實作的細節。

1. 建立一個新的controller,位于檔案夾src/main/java下。

MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
這個controller加上注解@RestController。@RestController注解相當于@ResponseBody和@Controller這兩個注解提供的功能的并集。這裡有一個知識點就是,如果用注解@RestController定義一個Controller,那麼這個Controller裡的方法無法傳回jsp頁面,或者html,因為@ResponseBody注解在起作用,是以即使配置了視圖解析器 InternalResourceViewResolver也不會生效,此時傳回的内容就是@RestController定義的控制器方法裡傳回的内容。
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB

2. 以讀操作為例,通過注解@GetMapping定義了讀操作Restful API的url為bookmanage/read。

@RequestParam定義了url:bookmanage/read後面的參數為id或者name。讀操作最終将會使用我們在

裡介紹的方法,即通過@Autowired注入的BookRepository執行個體完成對MongoDB的操作。
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
3. 建立操作的源代碼:

@GetMapping("/bookmanage/create")

public Book create(

@RequestParam(value="id", defaultValue="") String id,

@RequestParam(value="name", defaultValue="noname") String name,

@RequestParam(value="author", defaultValue="noauthor") String author

){

     Book book = repository.save(new Book(id,name,author));

     return book;

}           
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB

4. 删除操作的源代碼:

@GetMapping("/bookmanage/delete")

public boolean delete(

@RequestParam(value="id", defaultValue="") String id

){

    //if no record

     if(repository.findById(id)==null)

           return false;

     // do database delete

     repository.deleteById(id);

    return true;

}           
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB

本教程的完整代碼在我的github上:

MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB

要擷取更多Jerry的原創技術文章,請關注公衆号"汪子熙"或者掃描下面二維碼:

MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB
MongoDB最簡單的入門教程之五-通過Restful API通路MongoDB