Complete automated integration based on SpringBoot2 & MongoDB

Source: Internet
Author: User
Tags install mongodb mongodb

MongoDB is generally used in enterprise projects to store document information, image resources, etc., MONGODB content is completely stored in the form of JSON string, so we can get the data by simple deserialization to complete the entity class within the project, but this process is automatic, We do not need to do the deserialization process manually.
This chapter aims
Complete the simple springboot and MongoDB automation integration, let us like to use the form of SPRING-DATA-JPA to complete MONGODB data operation.

001
Spring Boot Core Technology
Explain springboot some of the core components of enterprise-level

002
Spring Boot Core Technical Section source code
Spring Boot Core Technology Brief book each article code cloud corresponding source code

003
Spring Cloud Core Technology
A comprehensive overview of spring cloud core technology

004
Spring Cloud Core Technology Chapter Source
Spring Cloud Core Technology book each article corresponding to the source code

005
QUERYDSL Core Technology
Fully explain QUERYDSL core technology and Springboot integration based SPRINGDATAJPA

006
SPRINGDATAJPA Core Technology
Fully explain SPRINGDATAJPA core technology

007
Springboot Core Technology Learning Catalogue
The Learning directory of the Springboot system,

Prepare Mongdb
We use the installation method provided by MongoDB, the following is the official installation of the corresponding system documentation:

Installing MongoDB under Linux
Installing MongoDB under Windows
Install MongoDB under OSX

Create user
We need to create a user, for use in this chapter, if you are OS X, simply open the terminal input MONGO command to access the MongoDB management interface.

    1. Create a database
      Using use test; command to create a database named test
    2. User who created the database owner role
      Db.createuser (
      {
      User: "Test",
      PWD: "123456",
      Roles: [{role: ' Dbowner ', DB: ' Test '}]
      }
      );
      After the user is created, the code for this chapter can be encoded, and then we need to make an environment connection to manipulate the data after the environment has been completed.

Building projects
We use idea to create a new Springboot project, add the dependencies we need in this chapter in the Pom.xml configuration file, as follows:
<dependencies>

org.springframework.boot spring-boot-starter-data-mongodb Org.projectlombok Lombok true Com.alibaba fastjson 1.2.44 org.springframework.boot spring-boot-starter-test test Based on MongoDB's dependence, we can see the spring family-style design, which classifies all operational data dependencies into SPRING-BOOT-STARTER-DATA-XXX, We are more commonly used to such as: SPRING-BOOT-STARTER-DATA-JPA, Spring-boot-starter-data-redis and so on. Mongorepositoryspring-boot-starter-data-mongodb does use the same approach as SPRING-BOOT-STARTER-DATA-JPA to complete the generation of interface proxy classes, and provides some common common methods of single object operation, Mongorepository interface function and jparepository consistent, inherit the interface of the business data interface can provide a spring IOC managed by the proxy implementation class, This completes the injection of the proxy implementation class as we inject the business data interface. No more nonsense, let's just create a data interface named Customerrepository that inherits Mongorepository , as follows:/** * Customer Data Interface * inherits from Mongorepository interface * * @author:
* =============================== * Created with idea. * DATE:2018/3/28 * Time: PM 7:41 * ================================ */public interface Customerrepository extends Mongorepository {}mongorepository The same is true of two generic parameters, T: entity class type. Pk:t the primary key type within the entity class, such as String. Custom entity classes we use the Customer entity class as a generic parameter within the Customerrepository interface, and we simply create the customer entity class, as follows: @Datapublic class Customer Implements Serializable {/** * customer number */@Id public string Id;/** * Customer Name */public string firstName;/** * Customer Last Name */public String LastName; Public Customer (String firstName, String lastName) {this.firstname = firstName; this.lastname = LastName;}} We also need to set the primary key by @id annotations, but the value of this primary key is automatically generated by MongoDB, and the resulting primary key value is unique. Add configuration code is ready, we just need to add some of MongoDB configuration information is done, below we need to add the following configuration in the Application.yml configuration file: Spring:application:name: Spring-boot-mongodb data:mongodb:uri:mongodb://localhost/test username:test Password: 123456 the test within the URI configured above is the name of the database, username configures our custom user name, and password is configured to customize the user-set password. The code above is all written and we need to test it. To see if our customerrepository has come into effect. Test we use the Commandlinerunner interface for a simple project run to perform data operations within the customer document, modify the Chapter51application entry class, add a command The implementation of the Linerunner interface is as follows:/** * Program Entry class * @author Yuqiyu */@SpringBootApplicationpublic class Chapter51application implements CommandlinerUnner {/** * Logger instance * * Static Logger logger = Loggerfactory.getlogger (chapter51application.class);/** * Customer Data Interface Note Enter */@Autowired private customerrepository repository; public static void Main (string[] args) {Springapplication.run (chapter51application.class, args); Logger.info ("" "" "" Springboot Integrated MongoDB boot complete. "" "" ""; } @Override public void run (String ... args) {//delete all Repository.deleteall ();///Add a data Repository.save ("to", "From the Yu")); Query all Logger.info (json.tojsonstring (Repository.findall ())); }} In the Run method to delete the entire contents of the customer document to perform the operation of saving data query out the contents of the saved data below we run the next program to view the effect of the console, as follows: [{"FirstName": "On", "id": " 5ad4be1cab73ac0bdc23bd9a "," LastName ":" Yu "}]" "" "Springboot integration MongoDB start complete." "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" " In the above mentioned the Special ID this field, which is a distributed uniqueness of the field value, is a short plate of the MD5 format of the string. Modify the default scan path if you do not intend to use the Springboot default scan path (springboot default scan Xxxapplication class and all children of the package) can be configured by @enablemongorepositories annotations BasePack The Ages property completes the scan of the custom MongoDB Mongorepository implementation class as follows: @SpringBootApplication @enablemongorepositories (basepackages = "Com.hengyu.chapter51 ") public class Chapter51application implements Commandlinerunner {} This chapter briefly explains the Springboot integrated MongoDB, which has the same data operation as JPA, and the data interface allows us to manipulate the data in the MongoDB document using the same method as JPA, by inheriting the mongorepository. Thus reducing the cost of learning.

Complete automated integration based on SpringBoot2 & 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.