Blasting column - springboot2 Integrating MongoDB cache commodity information in X Series tutorials

Posted by hame22 on Mon, 20 Dec 2021 19:33:14 +0100

preface

In the previous chapter, Yige} introduced how to integrate Redis in SpringBoot, and then realized the caching of the content queried in MySQL into Redis. In fact, if we want to achieve caching effect, we can also use another NoSQL type database, MongoDB. This article will take you to integrate MongoDB in SpringBoot and learn the basic use of MongoDB.
I MongoDB

1. Introduction to mongodb

MongoDB comes from the English word "Humongous" and the Chinese meaning is "huge". It is a high-performance, open source and modeless document database based on distributed file storage written in C + + language. It belongs to a popular NoSql database and can be applied to enterprises of all sizes, industries and various applications.
2. MongoDB data structure

The traditional relational database is generally composed of three levels: database, table and record, while MongoDB is composed of three levels: database, collection and document object. The collection in MongoDB corresponds to the tables in the relational database, but there are no concepts of columns, rows and relationships in the collection, which reflects the characteristics of schema freedom.

The data structure supported by MongoDB is very loose. It is a bjson format similar to json, so it can store complex data types. The following is the data organization type diagram of MongoDB:


MongoDB stores data as a document, and the data structure consists of key value (key = > value) pairs. A MongoDB document is similar to a JSON object. Field values can contain other documents, arrays, and document arrays.
3. MongoDB features

  • Mongo's biggest feature is that the query language he supports is very powerful. Its syntax is a bit similar to the object-oriented query language. It can almost realize most functions similar to single table query of relational database, and also supports indexing of data.

  • MongoDB is a document storage oriented database, which is relatively simple and easy to operate.

  • You can set the index of any attribute in MongoDB records (such as FirstName="Sameer",Address="8 Gandhi Road") to achieve faster sorting.

  • You can create data images locally or over the network, which makes MongoDB more scalable.

  • If the load increases (requires more storage space and stronger processing power), it can be distributed on other nodes in the computer network, which is the so-called fragmentation.

  • Mongo supports rich query expressions. The query instruction uses JSON tags, which can easily query the embedded objects and arrays in the document.

  • MongoDb can use the update() command to replace the completed document (data) or some specified data fields.

  • Map/reduce in Mongodb is mainly used for batch processing and aggregation of data.

  • Map and Reduce. The map function calls emit(key,value) to traverse all records in the collection, and passes the key and value to the Reduce function for processing.

  • The Map function and Reduce function are written in Javascript and can be accessed through dB Run command or MapReduce command to perform MapReduce operation.

  • GridFS is a built-in function in MongoDB, which can be used to store a large number of small files.

  • MongoDB allows scripts to be executed on the server. You can write a function in Javascript and execute it directly on the server. You can also store the definition of the function on the server and call it directly next time.

  • MongoDB supports various programming languages: RUBY, PYTHON, JAVA, C + +, PHP, c# and other languages.

  • MongoDB is easy to install.

II Integrating MongoDB in Spring Boot

1. MongoDB installation process

I won't show you the installation process of MongoDB database here. It's basically a fool installation.
2. Create a web project

According to our previous experience, we create a SpringBoot Web program. The specific process is omitted.

3. Add dependency

In POM Add the dependent package of MongoDB to the XML file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

4. Create application YML profile
Create application YML file, where the MongoDB database is configured.

server:
  port: 8080
spring:
  application:
    name: spirng-boot-mongodb
  data:
    mongodb:
      host: localhost   #Same as 127.0 zero point one
      port: 27017
      database: db01    #Specify the database for the operation

5. Create an entity class

5.1 relevant notes in mongodb

  • @Id - the unique Id of the document, which is ObjectId in mongodb. It is unique and consists of timestamp + machine Id + process Id + self incrementing counter (to ensure that the IDs generated in the same second do not conflict).

  • @Document - declare the document entity class of this class as mongodb, and specify the document name corresponding to this class through the collection parameter@ Document(collection = "mongodb") mongodb correspondence table

  • @Indexed - declare that the field needs an index. Indexing can greatly improve query efficiency.

  • @CompoundIndex - the declaration of composite index. Building composite index can effectively improve the query efficiency of multi field.

  • @Transient - maps ignored fields that are not saved to mongodb.

  • @PersistenceConstructor - declares a constructor that instantiates the data taken from the database as an object. The value passed in by this constructor is the data taken from DBObject.

5.2 create a Product entity class

Here I create a Product entity class to encapsulate the commodity information in the database.

server:
  port: 8080
spring:
  application:
    name: spirng-boot-mongodb
  data:
    mongodb:
      host: localhost   #Same as 127.0 zero point one
      port: 27017
      database: db01    #Specify the database package # com for the operation yyg. boot. entity;

import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
@Data
@ToString
@Document(collection = "product")
public class Product {

    @Id
    private String id;

    /**
     * Price
     */
    @Field("price")
    private Integer price;

    /**
     * Trade name
     */
    @Field("name")
    private String name;

    /**
     * Product introduction
     */
    @Field("info")
    private String info;

    /**
     * Product publisher
     */
    @Field("publisher")
    private String publisher;

    /**
     * Creation time
     */
    @Field("createTime")
    private Date createTime;

    /**
     * Modification time
     */
    @Field("updateTime")
    private Date updateTime;

}package com.yyg.boot.entity;

import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
@Data
@ToString
@Document(collection = "product")
public class Product {

    @Id
    private String id;

    /**
     * Price
     */
    @Field("price")
    private Integer price;

    /**
     * Trade name
     */
    @Field("name")
    private String name;

    /**
     * Product introduction
     */
    @Field("info")
    private String info;

    /**
     * Product publisher
     */
    @Field("publisher")
    private String publisher;

    /**
     * Creation time
     */
    @Field("createTime")
    private Date createTime;

    /**
     * Modification time
     */
    @Field("updateTime")
    private Date updateTime;

}

6. Create a Service implementation class

6.1 defining ProductService

Create an interface in the service package for CRUD operations on the database.

package com.yyg.boot.service;

import com.yyg.boot.entity.Product;

import java.awt.print.Book;
import java.util.List;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
public interface ProductService {

    String saveProduct(Product product);

    /**
     * Query all
     */
    List<Product> findAll();


    /***
     * Query by id
     */
    Product getProductById(String id);

    /**
     * Query by name
     */
    Product getProductByName(String name);

    /**
     * Update Object
     */
    String updateProduct(Product product);

    /***
     * delete object
     */
    String deleteProduct(Product product);

    /**
     * Delete by id
     */
    String deleteProductById(String id);

}

6.2 define ProductServiceImpl implementation class

Write a specific implementation class in the service layer to realize commodity information operation.

package com.yyg.boot.service.impl;

import com.yyg.boot.entity.Product;
import com.yyg.boot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveProduct(Product product) {
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        mongoTemplate.save(product);
        return "Added successfully";
    }

    @Override
    public List<Product> findAll() {
        return mongoTemplate.findAll(Product.class);
    }

    @Override
    public Product getProductById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, Product.class);
    }

    @Override
    public Product getProductByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, Product.class);
    }

    @Override
    public String updateProduct(Product product) {
        Query query = new Query(Criteria.where("_id").is(product.getId()));
        Update update = new Update().set("publisher", product.getPublisher())
                .set("info", product.getInfo())
                .set("updateTime", new Date());
        return "success";
    }

    @Override
    public String deleteProduct(Product product) {
        mongoTemplate.remove(product);
        return "success";
    }

    @Override
    public String deleteProductById(String id) {
        //findOne
        Product product = getProductById(id);
        //delete
        deleteProduct(product);
        return "success";
    }

}

7. Create Controller interface

We create a Controller and define several URL interfaces for testing.

package com.yyg.boot.web;

import com.yyg.boot.entity.Product;
import com.yyg.boot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("")
    public String saveProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    @GetMapping("")
    public List<Product> findAll() {
        return productService.findAll();
    }

    @GetMapping("/id/{id}")
    public Product findOne(@PathVariable("id") String id) {
        return productService.getProductById(id);
    }

    @GetMapping("/name/{name}")
    public Product findOneByName(@PathVariable("name") String name) {
        return productService.getProductByName(name);
    }

    @PostMapping("/update")
    public String update(@RequestBody Product product) {
        return productService.updateProduct(product);
    }

    @DeleteMapping("/delOne")
    public String delOne(@RequestBody Product product) {
        return productService.deleteProduct(product);
    }

    @DeleteMapping("/{id}")
    public String delById(@PathVariable("id") String id) {
        return productService.deleteProductById(id);
    }

}

8. Create Application entry class

Finally, we create an entry class to start the project.

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author One brother Sun
 * @Date Created in 2020/4/9
 * @Description Description
 */
@SpringBootApplication
public class MongoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoApplication.class, args);
    }

}

}

9. Project code structure
The following is the code structure of the project. You can refer to it.

10. Start the project for testing
10.1 create a blank database

After starting the project, we can manually create a blank database db01 in MongoDB.

10.2 test add interface function

Execute the add interface in Postman to test whether the data is added to the commodity library.

10.3 query MongoDB database

When we open MongoDB again, we can see the following information:

10.4 execute query test

At this time, we can query the commodity information in the browser and see the commodity information stored in MongoDB.

10.5 query by id

The following is the product information obtained by querying the id.

10.6 query by name

The following is the product information queried by name.


As for other interfaces, I won't test them one by one. They can be used normally.

 

If you need more tutorials, just scan the code on wechat

 

👆👆👆

Don't forget to scan the code to get the information [HD Java learning roadmap]

And [full set of learning videos and supporting materials of various disciplines]

 

Topics: Java Database MongoDB Cache