11th Chapter Springboot + MongoDB

Source: Internet
Author: User
Tags mongodb version

1. MongoDB Installation on Mac

  • Download mongodb,https://www.mongodb.org/
  • Unzip to a specified folder, such as:/users/enniu1/desktop/zjg/mongodb-osx-x86_64-3.2.6 (This is my MongoDB version)
  • Configure path
    • Input command: "VI ~/.bash_profile"
    • Add the following two sentence configurations:
      1 Export mongo_home=/users/enniu1/desktop/zjg/mongodb-osx-x86_64-3.2.6 2 Export path= $PATH: $MONGO _home/bin
      View Code
  • Create Data Catalog
    • Input command: "sudo mkdir-p/data/db"
  • Give Data directory Permissions
    • Input command: "sudo chmod 777/data/db"
  • Start
    • Input command: "Mongod"
  • Exit: Ctrl + C

Note Two errors:

    • If you do not create a directory to start directly, will error Http://stackoverflow.com/questions/7948789/mongodb-mongod-complains-that-there-is-no-data-db-folder
    • If the data directory permissions are not assigned, an error will be http://stackoverflow.com/questions/15229412/ Unable-to-create-open-lock-file-data-mongod-lock-errno13-permission-denied

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

2. Code (4 parts)

2.1, Com.xxx.firstboot.domain.Customer

1  PackageCom.xxx.firstboot.domain;2 3 Importorg.springframework.data.annotation.Id;4 5 /**6 * Test MongoDB7  */8  Public classCustomer {9     /**Ten * CID: This field is used for MongoDB "_id" index One * 1, need @id annotation A * 2, the name does not matter, anyway in MongoDB eventually will be converted to "_id" - * 3, defined as a string type, if defined as an integer may be the index will only be 0, there will be key duplication causes the database to plug in the case; - * 4, this type is also the ID of the primary key in the mongorepository generic type the      */ - @Id -     PrivateString CID; -     PrivateString FirstName; +     PrivateString Secondname; -  +      PublicString getcid () { A         returnCID; at     } -  -      Public voidsetcid (String CID) { -          This. CID =CID; -     } -  in      PublicString Getfirstname () { -         returnFirstName; to     } +  -      Public voidsetfirstname (String firstname) { the          This. FirstName =FirstName; *     } $ Panax Notoginseng      PublicString Getsecondname () { -         returnSecondname; the     } +  A      Public voidsetsecondname (String secondname) { the          This. Secondname =Secondname; +     } -  $}
View Code

Description: the generated colletion (similar to the table in MySQL) is the simple class name of the domain class, Eg.customer.

Attention:

    • CID: This field is used for MongoDB "_id" index
    • Need @id annotations
    • The name does not matter, anyway in MongoDB in the end will be converted to "_id"
    • is defined as a string type , if it is defined as an integer, the index will only be 0, and key duplication will cause the database to be plugged in.
    • The type is also the ID of the primary key in the mongorepository generic

2.2, Com.xxx.firstboot.mongo.CustomerRepository

1  PackageCom.xxx.firstboot.mongo;2 3 Importjava.util.List;4 5 Importorg.springframework.data.mongodb.repository.MongoRepository;6 7 ImportCom.xxx.firstboot.domain.Customer;8 9 /**Ten * Mongorepository<customer, integer> One * First parameter: T-operation Vo A * Second parameter: The primary key type of ID T - * Function: This interface implements the Crud method -  *  the * Note: - * 1, because boot uses spring-data-mongodb, so we do not need to write the implementation of the interface, - * When we run the program, SPRING-DATA-MONGODB will dynamically create - * 2, findbysecondname name is fastidious, Secondname (is the customer's property) if changed to LastName will be reported to find the property LastName error +  */ -  Public InterfaceCustomerrepositoryextendsMongorepository<customer, string> { +      PublicCustomer findbyfirstname (String firstname); A      PublicList<customer>findbysecondname (String secondname); at}
View Code

Description: This interface is our business interface.

Attention:

    • Inherit mongorepository<t, id> interface
      • T: Operating domain, such as Com.xxx.firstboot.domain.Customer
      • The primary key type of the Id:t (@ID decorated property), which is usually a string
      • The implementation class for this interface also implements CRUD operations
    • Our interface only needs to define the definition of the method, do not need to implement , Spring-data-mongodb will be dynamically created when the program is running
      • The name of the method is fastidious, related to the attributes of domain (can be measured again)

2.3, Com.xxx.firstboot.web.CustomerController

1  PackageCom.xxx.firstboot.web;2 3 Importjava.util.List;4 5 Importorg.springframework.beans.factory.annotation.Autowired;6 Importorg.springframework.web.bind.annotation.RequestMapping;7 ImportOrg.springframework.web.bind.annotation.RequestMethod;8 ImportOrg.springframework.web.bind.annotation.RequestParam;9 ImportOrg.springframework.web.bind.annotation.RestController;Ten  One ImportCom.xxx.firstboot.domain.Customer; A Importcom.xxx.firstboot.mongo.CustomerRepository; -  - ImportIo.swagger.annotations.Api; the Importio.swagger.annotations.ApiOperation; -  - @RestController -@RequestMapping ("/customer") +@Api ("Customer-related APIs for testing MongoDB") -  Public classCustomercontroller { +  A @Autowired at     Privatecustomerrepository customerrepository; -  -@ApiOperation ("Add a Customer") -@RequestMapping (value = "/addcustomer", method =requestmethod.get) -      PublicCustomer Addcustomer (@RequestParam ("FirstName") String FirstName, -@RequestParam ("Secondname") String secondname) { inCustomer customer =NewCustomer (); - Customer.setfirstname (firstname); to Customer.setsecondname (secondname); +         returnCustomerrepository.save (customer); -     } the  *@ApiOperation ("Get all Customer") $@RequestMapping (value = "/getallcustomer", method =requestmethod.get)Panax Notoginseng      PublicList<customer>Getallcustomer () { -         returnCustomerrepository.findall (); the     } +  A@ApiOperation ("Get customer based on FirstName") the@RequestMapping (value = "/getcustomerbyfirstname", method =requestmethod.get) +      PublicCustomer Getcustomerbyfirstname (@RequestParam ("FirstName") String FirstName) { -         returnCustomerrepository.findbyfirstname (firstname); $     } $  -@ApiOperation ("Get multiple customer based on Secondname") -@RequestMapping (value = "/getcustomerbysecondname", method =requestmethod.get) the      PublicList<customer> Getcustomerbysecondname (@RequestParam ("Secondname") String secondname) { -         returnCustomerrepository.findbysecondname (secondname);Wuyi     } the  -@ApiOperation ("Delete Customer by ID") Wu@RequestMapping (value = "/deletecustomerbyid", method =requestmethod.get) -      Public BooleanDeletecustomerbyid (@RequestParam ("CID") (String CID) { About Customerrepository.delete (CID); $         return true; -     } -}
View Code

description : Inject directly into our own business interface, then do the appropriate operation.

At this point, you are ready to test. Only the default information for MongoDB is used at this time.

    • Host:localhost
    • port:27017
    • Database: Test
    • Collection:customer (Simple class name for domain Class)

2.4, Application.properties

View Code

Note : If you need to specify host, port, database, you need to configure the above information in the Application.properties file.

Attention:

    • The configuration must be prefixed with "spring.data.mongodb"
    • If it is mongo3.x, the host and port are useless and require a URI. (not tested)
    • URI = mongodb://host:port/ Database

3. Testing

Launch the app, start the MONGO service process, open swagger, and use the Robomongo client to observe the MongoDB storage situation.

The property is not set in Application.properties.

After setting the properties,

Reference:

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/example is an explanation of the sample code

http://www.jianshu.com/p/e59cd2dc5274 about the MongoDB primary key

Https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html about mongo2.x and 3.x to host, Support for port, URI configuration.

11th Chapter Springboot + MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.