第十一章 springboot + mongodb

來源:互聯網
上載者:User

標籤:

1、mongodb在mac上的安裝

  • 下載mongodb,https://www.mongodb.org/
  • 解壓縮到一個指定檔案夾,如:/Users/enniu1/Desktop/zjg/mongodb-osx-x86_64-3.2.6(這是我的mongodb的版本)
  • 配置PATH
    • 輸入命令:"vi ~/.bash_profile"
    • 添加如下兩句配置:
      1 export MONGO_HOME=/Users/enniu1/Desktop/zjg/mongodb-osx-x86_64-3.2.62 export PATH=$PATH:$MONGO_HOME/bin
      View Code
  • 建立資料目錄
    • 輸入命令:"sudo mkdir -p /data/db"
  • 賦予資料目錄許可權
    • 輸入命令:"sudo chmod 777 /data/db"
  • 啟動
    • 輸入命令:"mongod"
  • 退出:Ctrl+c

注意兩個錯:

  • 如果沒有建立目錄直接啟動,會報錯http://stackoverflow.com/questions/7948789/mongodb-mongod-complains-that-there-is-no-data-db-folder
  • 如果沒有賦予資料目錄許可權,會報錯http://stackoverflow.com/questions/15229412/unable-to-create-open-lock-file-data-mongod-lock-errno13-permission-denied

參考:https://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

 

2、代碼(4個部分)

2.1、com.xxx.firstboot.domain.Customer

 1 package com.xxx.firstboot.domain; 2  3 import org.springframework.data.annotation.Id; 4  5 /** 6  * 測試mongodb 7  */ 8 public class Customer { 9     /**10      * cid:該欄位用於mongodb的"_id"索引11      * 1、需要@Id註解12      * 2、取名無所謂,反正在mongodb中最後都會轉化為"_id"13      * 3、定義為String類型,如果定義為Integer可能索引只會是0,會出現key重複導致資料庫插不進去的情況;14      * 4、該類型也是MongoRepository泛型中主鍵的ID15      */16     @Id17     private String cid;18     private String firstname;19     private String secondname;20 21     public String getCid() {22         return cid;23     }24 25     public void setCid(String cid) {26         this.cid = cid;27     }28 29     public String getFirstname() {30         return firstname;31     }32 33     public void setFirstname(String firstname) {34         this.firstname = firstname;35     }36 37     public String getSecondname() {38         return secondname;39     }40 41     public void setSecondname(String secondname) {42         this.secondname = secondname;43     }44 45 }
View Code

說明:產生的colletion(類似於MySQL中的表)就是domain類的簡單類名,eg.customer。

注意:

  • cid:該欄位用於mongodb的"_id"索引
  • 需要@Id註解
  • 取名無所謂,反正在mongodb中最後都會轉化為"_id"
  • 定義為String類型,如果定義為Integer可能索引只會是0,會出現key重複導致資料庫插不進去的情況
  • 該類型也是MongoRepository泛型中主鍵的ID 

2.2、com.xxx.firstboot.mongo.CustomerRepository

 1 package com.xxx.firstboot.mongo; 2  3 import java.util.List; 4  5 import org.springframework.data.mongodb.repository.MongoRepository; 6  7 import com.xxx.firstboot.domain.Customer; 8  9 /**10  * MongoRepository<Customer, Integer>11  * 第一個參數:T 操作的vo12  * 第二個參數:ID T的主鍵類型13  * 作用:該介面實現了CRUD方法14  * 15  * 注意:16  * 1、由於boot使用了spring-data-mongodb,所以我們不需要寫該介面的實現,17  *   當我們運行程式的時候,spring-data-mongodb會動態建立18  * 2、findBySecondname命名是有講究的,Secondname(是Customer的屬性)若改為lastname就會報找不到屬性lastname的錯誤19  */20 public interface CustomerRepository extends MongoRepository<Customer, String> {21     public Customer findByFirstname(String firstname);22     public List<Customer> findBySecondname(String secondname);23 }
View Code

說明:該介面就是我們的業務介面。

注意:

  • 繼承MongoRepository<T, ID>介面
    • T:操作的domain,例如com.xxx.firstboot.domain.Customer
    • ID:T的主鍵類型(@ID修飾的屬性),通常就是String
    • 該介面的實作類別也實現了CRUD操作
  • 我們的介面只需要定義方法的定義,不需要做實現,spring-data-mongodb會在程式啟動並執行時候動態建立
    • 方法的命名是有講究的,與domain的屬性有關(可以再測測) 

2.3、com.xxx.firstboot.web.CustomerController

 1 package com.xxx.firstboot.web; 2  3 import java.util.List; 4  5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestMethod; 8 import org.springframework.web.bind.annotation.RequestParam; 9 import org.springframework.web.bind.annotation.RestController;10 11 import com.xxx.firstboot.domain.Customer;12 import com.xxx.firstboot.mongo.CustomerRepository;13 14 import io.swagger.annotations.Api;15 import io.swagger.annotations.ApiOperation;16 17 @RestController18 @RequestMapping("/customer")19 @Api("customer相關的API,用於測試mongodb")20 public class CustomerController {21 22     @Autowired23     private CustomerRepository customerRepository;24 25     @ApiOperation("增加一個Customer")26     @RequestMapping(value = "/addCustomer", method = RequestMethod.GET)27     public Customer addCustomer(@RequestParam("firstname") String firstname,28                                 @RequestParam("secondname") String secondname) {29         Customer customer = new Customer();30         customer.setFirstname(firstname);31         customer.setSecondname(secondname);32         return customerRepository.save(customer);33     }34 35     @ApiOperation("擷取所有的Customer")36     @RequestMapping(value = "/getAllCustomer", method = RequestMethod.GET)37     public List<Customer> getAllCustomer() {38         return customerRepository.findAll();39     }40 41     @ApiOperation("根據firstname擷取Customer")42     @RequestMapping(value = "/getCustomerByFirstname", method = RequestMethod.GET)43     public Customer getCustomerByFirstname(@RequestParam("firstname") String firstname) {44         return customerRepository.findByFirstname(firstname);45     }46 47     @ApiOperation("根據secondname擷取多個Customer")48     @RequestMapping(value = "/getCustomerBySecondname", method = RequestMethod.GET)49     public List<Customer> getCustomerBySecondname(@RequestParam("secondname") String secondname) {50         return customerRepository.findBySecondname(secondname);51     }52 53     @ApiOperation("根據id刪除Customer")54     @RequestMapping(value = "/deleteCustomerById", method = RequestMethod.GET)55     public boolean deleteCustomerById(@RequestParam("cid") String cid) {56         customerRepository.delete(cid);57         return true;58     }59 }
View Code

說明:直接注入我們自己的業務介面,然後進行相應的操作即可。

此時,就可以進行測試了。只是此時使用的都是mongodb的預設資訊。

  • host:localhost
  • port:27017
  • 資料庫:test
  • collection:customer(domain類的簡單類名)

2.4、application.properties

View Code

說明:如果需要指定host、port、資料庫,需要在application.properties檔案中配置以上資訊。

注意:

  • 配置必須以"spring.data.mongodb"為首碼
  • 如果是mongo3.x的話,host和port沒用,需要uri。(未測過)
  • uri = mongodb://host:port/資料庫

 

3、測試

啟動應用,啟動mongo服務進程,開啟swagger,使用robomongo用戶端觀察mongodb儲存情況。

沒有在application.properties中設定屬性。

設定屬性後,

 

參考:

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-mongodb

https://spring.io/guides/gs/accessing-data-mongodb/ 其中的例子就是對sample代碼的解釋

http://www.jianshu.com/p/e59cd2dc5274 關於mongodb主鍵

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html 關於mongo2.x與3.x對host、port、uri配置的支援。

第十一章 springboot + mongodb

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.