第十一章 springboot + mongodb(簡單查詢)

來源:互聯網
上載者:User

標籤:xxx   stack   dom   ota   add   this   com   分享   目錄   

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
  • 建立資料目錄
    • 輸入命令:"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.Custome

package com.xxx.firstboot.domain;import org.springframework.data.annotation.Id;/** * 測試mongodb */public class Customer {    /**     * cid:該欄位用於mongodb的"_id"索引     * 1、需要@Id註解     * 2、取名無所謂,反正在mongodb中最後都會轉化為"_id"     * 3、定義為String類型,如果定義為Integer可能索引只會是0,會出現key重複導致資料庫插不進去的情況;     * 4、該類型也是MongoRepository泛型中主鍵的ID     */    @Id    private String cid;    private String firstname;    private String secondname;    public String getCid() {        return cid;    }    public void setCid(String cid) {        this.cid = cid;    }    public String getFirstname() {        return firstname;    }    public void setFirstname(String firstname) {        this.firstname = firstname;    }    public String getSecondname() {        return secondname;    }    public void setSecondname(String secondname) {        this.secondname = secondname;    }}
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

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

package com.xxx.firstboot.web;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.xxx.firstboot.domain.Customer;import com.xxx.firstboot.mongo.CustomerRepository;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;@RestController@RequestMapping("/customer")@Api("customer相關的API,用於測試mongodb")public class CustomerController {    @Autowired    private CustomerRepository customerRepository;    @ApiOperation("增加一個Customer")    @RequestMapping(value = "/addCustomer", method = RequestMethod.GET)    public Customer addCustomer(@RequestParam("firstname") String firstname,                                @RequestParam("secondname") String secondname) {        Customer customer = new Customer();        customer.setFirstname(firstname);        customer.setSecondname(secondname);        return customerRepository.save(customer);    }    @ApiOperation("擷取所有的Customer")    @RequestMapping(value = "/getAllCustomer", method = RequestMethod.GET)    public List<Customer> getAllCustomer() {        return customerRepository.findAll();    }    @ApiOperation("根據firstname擷取Customer")    @RequestMapping(value = "/getCustomerByFirstname", method = RequestMethod.GET)    public Customer getCustomerByFirstname(@RequestParam("firstname") String firstname) {        return customerRepository.findByFirstname(firstname);    }    @ApiOperation("根據secondname擷取多個Customer")    @RequestMapping(value = "/getCustomerBySecondname", method = RequestMethod.GET)    public List<Customer> getCustomerBySecondname(@RequestParam("secondname") String secondname) {        return customerRepository.findBySecondname(secondname);    }    @ApiOperation("根據id刪除Customer")    @RequestMapping(value = "/deleteCustomerById", method = RequestMethod.GET)    public boolean deleteCustomerById(@RequestParam("cid") String cid) {        customerRepository.delete(cid);        return true;    }}
View Code

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

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

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

2.4、application.properties

1 #mongodb note:mongo3.x will not use host and port,only use uri2 spring.data.mongodb.host=192.168.21.543 spring.data.mongodb.port=270174 spring.data.mongodb.uri=mongodb://192.168.21.54:27017/myfirstMongodb

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

注意:

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

 

3、測試

啟動應用,啟動mongo服務進程,開啟swagger,使用robomongo或者mongobooster用戶端觀察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配置的支援。

http://blog.didispace.com/springbootmongodb/ 主鍵為Long 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.