Code word is not easy, like collection, form a habit! Original author public number: Bigsai, common progress. More wonderful looking forward to sharing with you! MongoDB from site to Buddha (introduction, installation, add, delete, change, check) SpringBoot integration MongoDB(implementation of a simple cache)

Course of learning

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.

Before you use it, you should have the IDEA compiler on your own computer to create projects, MongoDB database and Studio 3T(studio3t.com/).

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.And then over the next few days, you might be wondering how to implement a feature like this, in this case with SpringBoot+MongoDBSimple version of logistics order system. 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.

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.

Design the database according to the E-R diagram. In our simple design, some of the data is like this: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:

1.2 Creating a SpringBoot Project

First, open IDEA to create the project and select Create SpringBoot project:Then fill in both Gruop and AritifactcomandmongodemoJava Version Select Version 8.

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:

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
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;/ / operation
    private String operator;/ / operator
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
    private Date operationTime;// The operation time
    private String address;/ / address
    private String details;// Note details

    public  logistics(a){}
    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(a) {
        return orderId;
    }
    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }
    public String getOperator(a) {
        return operator;
    }
    public void setOperator(String operator) {
        this.operator = operator;
    }
    public Date getOperationTime(a) {
        return operationTime;
    }
    public void setOperationTime(Date operationTime) {
        this.operationTime = operationTime;
    }
    public String getAdress(a) {
        return address;
    }
    public void setAdress(String address) {
        this.address = address;
    }
    public String getDetails(a) {
        return details;
    }
    public void setDetails(String details) {
        this.details = details;
    }
    public String getOperation(a) {
        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;/ / state
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
    private Date orderTime;// Order time
    private String shipper;/ / shipper
    private String shippingAdress;// Shipping address
    private long shipperPhone;// Shipper's phone
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
    private Date shipTime;// Shipping time
    private String recevier;/ / receiver
    private String recevierAddress;// Receiver address
    private long receviePhone;// Recipient number
    private List<logistics>logistics;// Logistics information

    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 and complete it yourself
}

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 it in the static folderindex.html.addlogistics.html.addorder.html.ordermanage.html. Enter theLayui websiteDownload layui’s JS and CSS files. Decompress the core file and place it in static. toJQuery官网Jquery-3.5.1.min.js; static create js folder and put jquery js file in it.

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:

<! DOCTYPEhtml>
<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>
        <! -- Header (works with layui's existing horizontal navigation) -->

        <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 (with layui's existing vertical navigation) -->
            <ul class="layui-nav layui-nav-tree"  lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="javascript:;">The order management</a>
                    <dl class="layui-nav-child">
                        <dd><a href="ordermanage.html" target="container">The order management</a></dd>
                        <dd><a href="addorder.html" target="container">Order to add</a></dd>
                        <dd><a href="addlogistics.html" target="container">Logistics add</a></dd>
                    </dl>
                </li>
            </ul>
        </div>
    </div>

    <div class="layui-body">
        <! Content body area -->
        <iframe src="addorder.html" name="container" width="100%" height="100%"></iframe>
    </div>


    <div class="layui-footer">
        <! -- Bottom fixed area -->Bigsai take you learn</div>
</div>
<script src="layui/layui.js"></script>
<script src="layui/modules/jquery.js"></script>
<! --<script src="layui/main.js"></script>-->
<script>
   // JavaScript code area
    layui.use('element'.function(){
        var $ = layui.jquery
            ,element = layui.element; // Tab-switching functions, switch event monitoring, etc., need to rely on the Element module
        // Trigger the event
        var active = {
            tabAdd: function(){
                // Add a Tab entry
                element.tabAdd('demo', {
                    title: 'New option'+ (Math.random()*1000|0) // for demonstration purposes
                    ,content: 'content'+ (Math.random()*1000|0),id: new Date().getTime() // The specified id is usually used in practice})},tabDelete: function(othis){
                // Delete the specified Tab entry
                element.tabDelete('demo'.'44'); // Delete: "Merchandise management"


                othis.addClass('layui-btn-disabled'); },tabChange: function(){
                // Switch to the specified Tab
                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: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!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:

// Create the order and pass the order object
 public  void addorder(order order)
 {
     mongoTemplate.insert(order,"order");
 }
Copy the code

In the code above:

  • The inserted statement ismongoTemplate.insert(order,"order"), the first parameter is the inserted document record, and the second parameter"order"Is the Collections under the corresponding database of connected MongoDB.

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("In shipment");
     order.setOrderTime(new Date());
     order.setShipTime(new Date());
     orderService.addorder(order);
     return "Added successfully";
 }
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:

<! DOCTYPEhtml>
<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-elem-quote layui-text">
            <span>To increase the order</span>
        </blockquote>
        <form class="layui-form col-lg-5 " action="addorder" method="post">

            <div class="layui-form-item">
                <label class="layui-form-label">The 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's 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">Shipper's address</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">Shipper's phone</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">Name of recipient</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 class="layui-form-label">Addressee address</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 mobile 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>
            </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

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.

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 the 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 "Added successfully";
}
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:

<! DOCTYPEhtml>
<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-elem-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">The 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">The 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">The 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">The operating address</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">note</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 layui-btn-primary">reset</button>
                </div>
            </div>
        </form>
    </div>
</section>
</body>
<script type="text/javascript" src="layui/layui.js"></script>

Copy the code

In this way, the front end is written and program access is performedlocalhost:8080, click Add Logistics, add logistics information according to the order number 1001.

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

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.

4.1 Back-end

Start by writing the getOrderById() function in OrderService to query the order record based on the order ID. The specific code is:

 // Query logistics by id
 public order getOrderById(int id)
 {
     Query query = new Query(Criteria.where("_id").is(id));
     order order=mongoTemplate.findOne(query, order.class);
     return  order;
 }
Copy the code

Among them:

  • Query object to assist us to achieve conditional Query of data to be updated, which means that the Query condition is also: the _id field in MongoDB is the record with the id passed in.
  • Mongotemplate.findone (query, order.class), mongotemplate.findone (query, order.class), mongotemplate.findone (query, order.class), mongotemplate.findone (query, order.class), mongoTemplate.
  • The findAll() method can be used to query multiple records, and returns a collection type of List.

After writing the Service, we write the GetorderbyID interface in orderController to handle user requests and parameters and call the GetorderbyID () method of orderService to return the JSON string serialized by the Order object to the front end. The specific code is:

 @GetMapping("getorderbyid")
 public order getOrderById(int id)
 {
     order order=orderService.getOrderById(id);
     return  order;
 }
Copy the code

This completes the back-end part, requiring only the front-end rendering data.

4.2 Front End:

After the back-end design is completed, the front-end is needed to realize interaction. Ajax is used here to realize interaction. The front-end page clicks buttons and JavaScript sends requests with parameters, and the back-end queries MongoDB and returns results to the front-end rendering. The data of each logistics order will be visually displayed.

The front end writes the following in orderManage.html:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="layui/css/layui.css">
</head>
<body>
<blockquote class="layui-elem-quote layui-text">The order management</blockquote>
<div class="layui-form-item">
    <div class="layui-inline">
        <label class="layui-form-label">The order number</label>
        <div class="layui-input-inline">
            <input type="tel" name="orderid" id="orderid"  autocomplete="off" class="layui-input">
        </div>
    </div>
    <button class="layui-btn"  id="seach" onclick="search()">search</button><br>
    <div style="padding: 20px; background-color: #F2F2F2;">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header" id="order"></div>
                    <div class="layui-card-body" id="orderbody">

                    </div>
                </div>
            </div>
        </div>
    </div>
    <ul class="layui-timeline" id="timezhou">

    </ul>
</div>
</body>
<script type="text/javascript" src="layui/layui.js"></script>
<script type="text/javascript" src="Js/jquery - 3.5.1 track of min.. js"></script>
<script type="text/javascript">
    function  search() {/ / according to
        var orderid = $("#orderid").val();
        $("#orderbody").html(' ');
        $("#timezhou").html(' ');
        $.ajax( {
            url:"getorderbyid".data: {'id':orderid
            },
            method:'GET'.success:function (order) {$("#order").html('Order No. :'+orderid+'('+order['status'] +') ');
                $("#orderbody").append('From:'+order['shipper'] +'  Sender mobile phone: '+order['shipperPhone'] +'  Sender address: '+order['shippingAdress'] +'  Order time: '+order['shipTime']);
                $("#orderbody").append('

To: '
+order['recevier'] +'  Harvester phone: '+order['receviePhone'] +'  Reaper address: '+order['recevierAddress']); var logistics=order['logistics']; console.log(logistics); for(var i=logistics.length-1; i>=0; i--) {console.log(logistics[i]); $("#timezhou").append(' <li class="layui-timeline-item">\n' + '< I class = "layui - the icon layui - timeline - axis" >  < / I > \ n' + '
\n'
+ '

'

+'('+logistics[i].operation+') '+logistics[i].operationTime+ '

'

+logistics[i].operator+'  '+logistics[i].details+'<br>'+logistics[i].adress); if(logistics[i].phone! =0) {$("#timezhou").append('<br>'+logistics[i].phone); } $("#timezhou").append(' </p>\n' + ' \n' + ' '); }},error:function (order) { layer.msg(order) } }) }
</script> Copy the code

Where Ajax will return the value through the assembly of the render, will fill the data area first set the ID attribute, and then use JavaScript to render the data to that part, the core idea is in the search() function.

Start the program, accesslocalhost:8080Click Order Management to query the logistics situation of the order no. 1001.

Add more logistics information of the order by using the above added logistics information to simulate more processes. The query result is:

Step 5 Order deletion

As a manager, you may occasionally encounter special circumstances that require you to delete an order, and this operational requirement is also necessary. Here, delete an order by ID is implemented. When deleting an order, we generally query some data and results of the order first, and then delete the corresponding records according to the ID of the query.

5.1 Back-end Modules

First, write the deleteOrderById() function in orderService to delete by ID, and write the getAllorder() function to query all orders.

// Delete records by id
public boolean deleteOrderById(int id)
{
    Query query = new Query(Criteria.where("_id").is(id));
    mongoTemplate.remove(query,order.class,"order");
    return  true;
}
// Query all orders
public List<order>getAllorder()
{
    List<order>list=mongoTemplate.findAll(order.class,"order");
    return  list;
}
Copy the code

Among them:

  • Mongotemplate. remove(query,order.class,”order”); mongotemplate. remove(query,order.class,”order”); The first parameter is the location condition of the record to be deleted, the second parameter is the Java type of the data to be deleted, and the third parameter is the name of the collection where the data to be deleted resides.
  • Mongotemplate.findall (order.class,”order”); mongotemplate.findall (order.class,”order”); The first parameter is the type of Java object to which the query result is converted, which helps you handle it automatically. The second parameter is the collection to be queried.

After writing the Service, write the DeleteByID interface and the GetallOrder interface in orderController to receive and process the request to delete the order and the request to fetch all the orders, respectively.

 @GetMapping("deletebyid")
 public String deleteById(int id)
  {
      orderService.deleteOrderById(id);
      return "Success";
  }
  @GetMapping("getallorders")
  public Map<String,Object> getAllOrder(a)
  {
      Map<String,Object>map=new HashMap<>();
      List<order> list=orderService.getAllorder();
      map.put("code"."0");
      map.put("count",list.size());
      map.put("data",list);
      return  map;
  }
Copy the code

The getallOrder interface returns a Map

data format. This is because the Layui table requires a specific JSON format, so we return data stored in the Map. Start access localhost: 8080 / getallorders you will see the following format:
,object>

5.2 Front End

We’ll also write the front end in orderManage.html. In this page to achieve order query and management functions. Start by adding a table attribute to the body div to represent a table:

<div class="larry-personal-body clearfix">
     <table class="layui-hide"  id="ordertable" lay-filter="ordertable"></table>
</div>
Copy the code

The code to add an edit bar under the Body field is an edit object attached to the table, where the delete button is located.

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">Filter export on the right</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">The editor</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">delete</a>
</script>
Copy the code

Finally, add code for rendering tables and sending Ajax requests to the lowest script field:

layui.use('table', function(){ var table = layui.table; // Add () table.render({elem: '# orderTable ',url: 'getallOrders',page: false,toolbar: '#toolbarDemo',cols: [[// header {field: 'id', title: 'id', sort: true, Fixed: 'left',width:80},{field: 'id', title: 'id', sort: true, fixed: 'left',width:80},{field: 'orderTime', title: 'orderTime', sort:true,width:80},{field: 'recevierAddress', title: 'recevierAddress'},{field: 'recevier', title: 'orderTime', sort:true,width:80},{field: 'recevierAddress', title: 'Consignee ', edit:'text'},{field: 'receviePhone', title:' Consignee '},{field: 'shippingAdress', title: 'shipping address '},{field: 'shipper', title: 'shipper'},{field: 'shipperPhone', title: 'shipperPhone'},{field: 'status', title: 'shipping status'},{fixed: 'right, title:' operation ', the toolbar: '# barDemo, width: 150}}]]); On ('tool(orderTable)', function(obj){var data = obj.data; Console. log(obj) if(obj.event === 'del'){layer.confirm(function(index){$. Ajax ({url:' deleteById ', data: { 'id':data.id, }, method:'GET', traditional: true, success:function (msg) { layer.msg(msg); obj.del(); }, error:function (msg) { layer.msg(msg) } }); layer.close(index); }); } else if(obj.event === 'edit'){layer.msg(json.stringify (" you can edit the cell directly by clicking on it "))}}); });Copy the code

Among them:

  • Table. render is layui syntax, configure data URL and format, corresponding to each field data name and meaning, data can be rendered. Click delete to access the deleteByID interface of the back end and send the ID of this row of data to the back end. Upon receiving the request, the back end orderController will call orderService method to delete the corresponding data in MongoDB.

The specific location to be added is:

Start the program, accesslocalhost:8080Select * from logistics order where id = 1001;Check the page and MongoDB database again and you will find that the record with id 1001 has been deleted successfully:

conclusion

To this, MongoDB actual combat small project – a logistics order system is completed, I think you must be able to use MongoDB “operation a fierce as tiger”!

Review courses in this section, first introduced the directing the non-relational database from the macroscopic characteristics and scene, pick up a suit case from the scene as a case in this course – order to realize a logistics system, and then take you simple order case logic, and analysis of logistics in a relational database and directing a different way to handle it, Finally create Springboot integration MongoDB project to achieve a simple version of the logistics order system!

Of course, this section only takes you to get started with MongoDB, talking about some basic content and simple use. If you need to learn more about using MongoDB, you also need to learn more about MongoDB from the official website documents and other books and articles. It is a very popular non-relational database based on documents. Is a must master the technical point, hope you go farther! Class is over!

Don’t forget to order one after classzambrottaSupport! In addition, more exciting also please wechat searchbigsaiReply,bigsaiGet extra large GB PDF learning resources.