! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/d96b2e84f4574c0eb040292897839691)

We all know that MongoDB is a great non-relational document database, so you have to ask how we can use it and what are the scenarios? MongoDB application scenarios are very many, whether it is data storage or log storage more and more companies are using MongoDB, and today we also use MongoDB on the basis of SpringBoot to achieve a simple version of logistics order management system.

Case analysis

1.1 Case Analysis

I think most of us have shopping experience. When the goods are ordered, there will be a logistics number, and the logistics information will be updated according to this number in the next few days.

! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/75bae5b44fc6414b9e203a9c67a31b9b)

You may wonder how such a feature is implemented. In this case, a simple version of logistics order system is implemented through SpringBoot+MongoDB. Of course, the specific commercial implementation must consider a lot of details is also very complex, this case focuses more on the function implementation and MongoDB use.

1.2 Disassembly of core ideas

How is an order data generated and updated? First of all, an order data is generated when placing an order, and then the order goes through various logistics points to update the logistics information and order status. Finally, after the order status is updated, the data is basically no longer updated.

Ordering module: I think most people have seen the ordering process of express delivery or placed an order by themselves. The core is a form page to fill in the sender’s name, address, mobile phone and recipient’s name, address, mobile phone and other information. So the specific implementation here is also to fill in the sender and recipient information storage.

Logistics module: after an order is placed, it may go through several logistics locations before finally arriving at the destination. In terms of each logistics point, the managers of each logistics point add some logistics information to the logistics order, such as the arrival address, the current status of the order, contact information and so on. In this case, the logistics information of the order is also added through a form, and the logistics order ID is simultaneous.

! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/e43c660981f349ee9c5c714b8b6fed7a)

How should this data be stored? If a relational database is used, at least two tables may be used to store the Logistics information of a single order. An order information table stores some fixed field information of an order, and a Logistics information table stores dynamic Logistics changes. The association of the two tables is realized through the order ID.

! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/8ed4182411be41faae1f63d49f55a9b2)

Design the database according to the E-R diagram. In our simple design, some of the data is like this:

! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/1c7297a670b546fba21dc46e2c5a8e2e)

The ORDER_ID foreign key in the logistics table references the ID field in the ORDER table for association. Associative query is required when querying order data. The logistics order system can indeed be realized by using relational database, but the large amount of data may lead to performance bottlenecks that need to be optimized. If MongoDB is adopted, it can not only improve efficiency, but also make the process simpler.

The order is characterized by the fact that the order data needs to be updated at any time during the delivery process. The data structure needs to be flexible, which is very consistent with the document document model of MongoDB, and MongoDB supports GIS function, which is very suitable for MongoDB to support logistics business (simple version here does not use this function). In the logistics industry, orders are relatively independent, and there are few cross-order operations, but there are many creation and update (addition) operations. The logistics business model matches MongoDB very well. This course is a small example of using MongoDB to implement a logistics order system.

1.3 This case involves knowledge points

SpringBoot I believe you are familiar with SpringBoot. Due to the development of Spring and microservices, SpringBoot is becoming more and more popular and has become the mainstream framework for JavaWeb development.

SpringBoot is a new framework from the Pivotal team designed to simplify the initial setup and development process for new Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations. In this way, SpringBoot has become a leader in the booming field of Rapid Application development.

In short, SpringBoot is the current mainstream of Web development, simplifying Spring configuration and making web project development easier for developers. MongdoDB can be quickly integrated with SpringBoot, and MongoDB can be operated quickly and conveniently in the project.

MongoDB MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for Web applications. MongoDB is a product between relational database and non-relational database, non-relational database has the most rich function, the most like relational database. It supports a very loose data structure in the JSON-like BSON format, so it can store complex data types. The biggest feature of MongoDB is that the query language it supports is very powerful. Its syntax is similar to object-oriented query language, and it can almost achieve most functions similar to single table query of relational database, and also supports data index.

This case is a small case based on SpringBoot and MongoDB to achieve a logistics order system, the actual logistics scene needs to consider a lot of problems are more complex, this is to achieve a simple version of the logistics order system mainly for the use and learning of MongoDB.

1.4 Case implementation steps

After analyzing the case and understanding the knowledge point of case design, you can start to realize this case step by step. What this case wants to achieve is a small and complete logistics order management system of order creation, order information update, query and deletion. In the concrete implementation according to the following steps:

  1. Prep work: Create the database and project
  2. Order to add
  3. Update order
  4. Order query
  5. Order to delete

The environment for hot operation of the whole case is as follows:

  • Operating system: Windows10
  • JDK version: JDK8
  • Compiler: IDEA
  • MongoDB version: 4.4.0
  • MongoDB visual management tool: Studio 3T

Implementation steps

The first step is preparation

1.1 Creating a MongoDB Database

Mysql > create a database named test and create a set named order in the test database:

! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/de050f9c6be54246b03afe5479b53167)

1.2 Creating a SpringBoot Project

First, open IDEA to create the project and select Create SpringBoot project:

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/1e207a717ef443bf9d320e198f2349f9)

Then fill in COM and Mongodemo respectively when selecting Gruop and Aritifact, and select Java Version 8.

! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/8386fc3017a644239724eee606e35ed2)

When checking the module, check the Spring Web and MongoDB dependency modules here, select the appropriate location to create the project, and the project can be successfully created:

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/c8c36008841e4ae2a54db8ab92112a9c)

After you create a project, you need to do some preparatory work.

1.3 Creating Java Files

After creating the project, we need to do some preparatory work to complete the cache. We will first add a configuration connection to the database in the application.properties section of the project as follows: Uri =mongodb:// Address: port/database name. In this case, the local mongodb database is used. The default port is 27017 and the name of the mongodb database is test.

spring.data.mongodb.uri=mongodb://localhost:27017/test
1
Copy the code

This allows you to connect to and access the local MongoDB test database in your project.

Create controller, service, poJO folders in the com.mongodb directory, and create orderController class in the Controller folder, which is responsible for url and logic controller:

package com.mongodemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class orderController {
    private static Logger logger= LoggerFactory.getLogger(orderController.class);

}
Copy the code

Among them:

  • RestController declares the class as a controller, and each interface returns a JSON string to the front end.
  • The Logger object is used to print logs. In web projects we prefer to print logs using logs rather than directly to the console.

After the orderController is created, create the orderService. Java class under the Service folder and write the following:

package com.mongodemo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
public class orderService {
    private static Logger logger= LoggerFactory.getLogger(orderService.class);
    @Autowired
    MongoTemplate mongoTemplate;
}
Copy the code

Among them:

  • @service indicates that this class is a Service (transaction) that can be injected into other objects (Spring manages it for you).
  • @autoWired means to inject an object, followed by the injected object. MongoTemplate is an object already wrapped, an object that manipulates MongoDB in Spring.

After the service is created, we need to create the Logistics class and order class in the POJO to represent the specific logistics information and order information respectively. The logistics class is as follows. Please refer to the notes for the meanings of each field:

package com.mongodemo.pojo; import java.util.Date; public class logistics { private int orderId; // Order id private String operation; // Private String operator; // operator @jsonFormat (pattern = "YYYY-MM-DD HH: MM ", timeZone = "GMT+8") private Date operationTime; Private String address; // address private String details; Public logistics(){} public logistics(int orderId,String operation, String operator, Date operationTime, String address, String details) { this.orderId = orderId; this.operation=operation; this.operator = operator; this.operationTime = operationTime; this.address = address; this.details = details; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public Date getOperationTime() { return operationTime; } public void setOperationTime(Date operationTime) { this.operationTime = operationTime; } public String getAdress() { return address; } public void setAdress(String address) { this.address = address; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; }}Copy the code

The contents of the Order class are as follows:

package com.mongodemo.pojo; import java.util.Date; import java.util.List; public class order { private int id; // Order id private String status; @jsonFormat (pattern = "YYYY-MM-DD HH: MM ", timeZone = "GMT+8") private Date orderTime; // Order time private String shipper; // Private String shippingAdress; Private long shipperPhone; @jsonFormat (pattern = "YYYY-MM-DD HH: MM ",timezone = "GMT+8") private Date shipTime; Private String recevier; Private String recevierAddress; Private long receviePhone; Private List<logistics>logistics; Public order(int ID, String status, Date orderTime, String shipper, String shippingAdress, long shipperPhone, Date shipTime, String recevier, String recevierAddress, long receviePhone, List<com.mongodemo.pojo.logistics> logistics) { this.id = id; this.status = status; this.orderTime = orderTime; this.shipper = shipper; this.shippingAdress = shippingAdress; this.shipperPhone = shipperPhone; this.shipTime = shipTime; this.recevier = recevier; this.recevierAddress = recevierAddress; this.receviePhone = receviePhone; this.logistics = logistics; } // omit the get set method, complete}Copy the code

In the command, @jsonformat (pattern = “YYYY-MM-DD HH: MM”,timezone = “GMT+8”) is the JSON output format of the time class, which is used by the front-end.

1.4 Creating HTML files

Create index under static folder. HTML, addlogistics. HTML, the addorder. HTML. Ordermanage. HTML. Download layui JS and CSS files from layui’s official website. Decompress the core file and place it in static. Jquery-3.5.1.min. js; static; static; js;

! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/00beaff3414a4112a451c189be3f94e2)

The index. HTML file is the main UI page for background management, and the corresponding page for each small function page only needs to be written. Write the following in index.html:

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, Maximum-scale =1"> <title> Order management system </title> <link rel="stylesheet" href="layui/ CSS /layui.css"> </head> <body class="layui-layout-body"> <div class="layui-layout layui-layout-admin"> <div class="layui-header"> <div class="layui-logo">ordermanage</div> <! <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item"> <a href="javascript:; " > bigsai </a> </li> </ul> </div> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll"> <! -- Left navigation area (available with layui vertical navigation) --> <ul class="layui-nav layui-nav-tree" lay-filter="test" layui-nav-itemed"> <a class="" href="javascript:;" Order Management </a>< dl class="layui-nav-child"> < DD ><a href="ordermanage.html" target="container"> Order management </a></dd> <dd><a HTML "target="container"> Order add </a></dd> < DD ><a href=" addLogistics. HTML" target="container"> Logistics add </a></dd> </dl> </li> </ul> </div> </div> <div class="layui-body"> <! HTML name="container" width="100%" height="100%"></iframe> </div> <div class="layui-footer"> <! </div> <script SRC ="layui/layui.js"></script> <script src="layui/modules/jquery.js"></script> <! --<script SRC ="layui/main.js"></script>--> <script> function(){ var $ = layui.jquery ,element = layui.element; Var active = {tabAdd: function(){// Add a Tab element element.tabadd ('demo', {title: 'new option + (Math. The random () * 1000 | 0) / / for demonstration, content:' content '+ (Math) random () * 1000 | 0), id: New Date().getTime() // use the specified id})},tabDelete: Function (othis){// Delete the element element.tabDelete('demo', '44'); Othis. addClass('layui-btn-disabled'); // Delete: othis.addClass('layui-btn-disabled'); },tabChange: function(){// Switch to the specified Tab element element.tabchange ('demo', '22'); // Switch to: User management}}; }); </script> </body> </html>Copy the code

After opening the page, you can see the preliminary page of background management:

! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/e8a7c698912e459fb3e43e795343eb71)

The three menus on the left correspond to the created pages of OrderManage. HTML, addOrder. HTML, and addLogistics. Now that the preparatory work is complete, all you need to do is complete the specific operations. This course will focus on the back-end and MongoDB, and the front-end knowledge will be briefly introduced, which requires in-depth understanding and more research.

Step 2 Order addition

I think everyone will place an order, every time waiting for logistics information is there a full sense of expectation and joy!

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/5f9d4f90a64b4928ad7f10203144fc35)

Let’s take you to experience this little joy today. After completing the case, you can order as many orders as you want.

2.1 Back-end

First, write the addOrder function in orderService to add orders to MongoDB. The specific code is as follows:

Public void addOrder (order order) {mongoTemplate. Insert (order,"order"); }Copy the code

In the code above:

  • Mongotemplate.insert (order,”order”), the first parameter is the inserted document record, and the second parameter “order” is the Collections under the connected MongoDB corresponding database.

Write the AddOrder () interface in orderController to handle requests to add orders to the front end. The specific code is:

@Autowired orderService orderService; @postMapping (" addOrder ") public String addOrder (order order) {order.setStatus(" addOrder "); order.setOrderTime(new Date()); order.setShipTime(new Date()); orderService.addorder(order); Return "Add success "; }Copy the code

In the code above:

  • The @autoWired annotation is used to inject objects, and the following orderService is the injected object. OrderService is the injected object, and after injection, you don’t need to manually create the object and you can use it (Spring manages it for you).
  • PostMapping(” addOrder “) indicates a POST request interface whose address is addOrder.
  • Public String addOrder (order ORDER) function name arbitrary, function arguments can be corresponding to each field of the form and create an order object, but create an order object directly and the front-end form passes the corresponding name value will be directly assigned (save reassignment).
  • For simplicity, the order date and delivery date are the current system time, and the initial order status is in delivery by default.

2.2 Front End

With the support of the back-end part, we write the following in addOrder.html, mainly a form that sends data and requests to the server:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="layui/css/layui.css"> </head> <body> <section class="layui-larry-box"> <div class="larry-personal"> <blockquote Class =" layui-em-quote layui-text"> <span> Add order </span> </ blockQuote > <form class="layui-form col-lG-5" Action =" addOrder "method="post"> <div class="layui-form-item"> <label class="layui-form-label"> Order ID </label> <div class="layui-input-block"> <input type="text" name="id" autocomplete="off" class="layui-input" value="" > </div> </div> <div class="layui-form-item"> <label class="layui-form-label"> Shipper name </label> <div class="layui-input-block"> <input type="text" name="shipper" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"> <div class="layui-input-block"> <input type="text" name="shippingAdress" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label Class ="layui-form-label"> shipperPhone </label> <div class="layui-input-block"> <input type="text" name="shipperPhone" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label Class ="layui-form-label"> Recipient name </label> <div class="layui-input-block"> <input type="text" name="recevier" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label <div class="layui-form-label"> <div class="layui-input-block"> <input type="text" name="recevierAddress" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label Class ="layui-form-label"> Recipient phone </label> <div class="layui-input-block"> <input type="text" name="receviePhone" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <div Class ="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo"> add </button> <button type="reset" Class ="layui-btn layui-btn-primary"> reset </button> </div> </form> </div> </section> </body> <script type="text/javascript" src="layui/layui.js"></script>Copy the code

After writing, launch the program to go to localhost:8080, click Add Order, and then fill in the corresponding content in the form

! [](https://p26-tt.byteimg.com/large/pgc-image/4f628451bf2e456ea04aa0b9e44cb7d5)

Of course, you can write a second order to test it. After adding it, you will find that the order data has been successfully added to MongoDB.

! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/2bb9052d7b8e43d4a021e76741db3ce2)

Step 3 Order Update (Additional Order)

After the order is created, countless distribution companies and personnel begin to deliver logistics, and when we inquire, the logistics status information can be refreshed from time to time, and the specific logistics information can also be added.

3.1 Back-end

In the processing, we write the service first, to write the controller, writing in the orderService addLogisticsAndUpdateStatus () function, main implementation update order status and order of logistics. The specific code is:

/ / update logistics public void addLogisticsAndUpdateStatus (logistics logistics) {String status = logistics. GetOperation (); Query query = new Query(Criteria.where("_id").is(logistics.getOrderId())); Update update = new Update(); update.set("status", status); Update. Push ("logistics",logistics); mongoTemplate.upsert(query, update, order.class); }Copy the code

Among them:

  • Query object to assist us to Query the data to be updated according to the conditions, which means that the conditions for querying data are: the _ID field in MongoDB is the order ID corresponding to specific logistics.
  • The Update object sets the fields and data to be updated, the set() method updates the values of the corresponding fields directly, and the push() method appends values to the corresponding array. Because the order status needs to be updated directly using the set() method, and the logistics information is composed of multiple logistics data, push() needs to be appended to the record.
  • Mongotemplate. upsert(query, update, order.class) to commit the update operation, if it doesn’t exist in MongoDB then insert it into MongoDB.

After writing orderService, write an interface named updateOrder in orderController to handle the updated request and parameters and perform the updated operation as follows:

@PostMapping("updateorder") public String updateorder(logistics logistics) { logistics.setOperationTime(new Date()); orderService.addLogisticsAndUpdateStatus(logistics); Return "Add success "; }Copy the code

The same interface type for post type, receiving some parameters and then set the logistics operation time to the current time, the orderService addLogisticsAndUpdateStatus update () method of operation. This completes the back end.

3.2 Front-end

With the support of the back-end part, the front end we write the following in addlogistics. HTML, which is basically a form that sends data and update requests to the server:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="layui/css/layui.css"> </head> <body> <section class="layui-larry-box"> <div class="larry-personal"> <blockquote Class =" layui-em-quote layui-text"> <span> Add logistics information </span> </blockquote> <form class="layui-form col-lG-5" Action =" updateOrder "method="post"> <div class="layui-form-item"> <label class="layui-form-label"> Order ID </label> <div class="layui-input-block"> <input type="text" name="orderId" autocomplete="off" class="layui-input" value="" > </div> </div> <div class="layui-form-item"> <label class="layui-form-label"> Operation name </label> <div class="layui-input-block"> <input  type="text" name="operation" autocomplete="off" class="layui-input" value=""> </div> </div> <div Class ="layui-form-item"> <label class="layui-form-label"> operator </label> <div class="layui-input-block"> <input type="text" name="operator" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label Class ="layui-form-label"> <div class="layui-input-block"> <input type="text" name="adress" autocomplete="off" class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <label Class ="layui-form-label"> Remarks </label> <div class="layui-input-block"> <input type="text" name="details" autocomplete="off"  class="layui-input" value=""> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button Class ="layui-btn" lay-submit lay-filter="formDemo"> Add </button> <button type="reset" class="layui-btn" lay-submit lay-filter="formDemo" Layui-btn-primary "> reset </button> </div> </form> </div> </section> </body> <script type="text/javascript" src="layui/layui.js"></script>Copy the code

In this way, the front-end part is written, the execution program visits localhost:8080, click Add Logistics, and add logistics information according to the order number 1001.

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/1440f256fce549608680bb03a0a7d2c4)

After adding, check the order status and logistics data in MongoDB are updated (add) :

! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/fbab419f814c492996a655a29f4714c9)

Step 4 Order query

The addition and modification of the order have been completed. Of course, the very important query cannot be less, not less, but also the characteristic display. Here, the query can query the status and logistics of the corresponding order through an order number.

I won’t upload all of them due to space constraints. Try to find out first! Leave a comment below if you don’t reply

This article reprinted text, copyright belongs to the author, such as infringement contact xiaobian delete!

Original address: blog.csdn.net/qq_40693171…

Complete project code acquisitionPoint it