SpringBoot+MongoDB實現(xiàn)物流訂單系統(tǒng)的代碼
課程導(dǎo)學(xué)
我們都知道MongoDB是一款非常出色的非關(guān)系型文檔數(shù)據(jù)庫,你肯定會想問MongoDB這么強(qiáng),我們該怎么用或者有啥運用場景呢?
MongoDB的應(yīng)用場景非常多,無論是數(shù)據(jù)存儲還是日志存儲越來越多的公司在使用MongoDB,而我們今天也在SpringBoot基礎(chǔ)上使用MongoDB實現(xiàn)一個簡易版本的物流訂單管理系統(tǒng)。
在使用前,你自己的電腦上要有IDEA編譯器來創(chuàng)建項目,還要擁有MongoDB數(shù)據(jù)庫和Studio 3T(MongoDB可視化數(shù)據(jù)庫管理工具,下載地址https://studio3t.com/)。
案例分析
1.1 案例分析
我想,大部分人都應(yīng)該有著購物的經(jīng)歷,當(dāng)商品下單時就會出現(xiàn)一個物流單號,接下來幾天內(nèi)的物流信息會根據(jù)這個單號更新。
然后接下來的幾天可能會到達(dá)不同地點,進(jìn)行更新,你可能會好奇這樣一個功能是如何實現(xiàn),本案例就通過SpringBoot+MongoDB實現(xiàn)一個簡易版本的物流訂單系統(tǒng)。當(dāng)然具體實現(xiàn)商用肯定要考慮很多細(xì)節(jié)也很復(fù)雜,本案例更側(cè)重于功能實現(xiàn)和MongoDB使用。
1.2 核心思路拆解
一個訂單數(shù)據(jù)是如何產(chǎn)生和更新的呢?首先一個訂單數(shù)據(jù)由下單時產(chǎn)生,然后該訂單經(jīng)歷各個物流點更新物流信息和訂單狀態(tài),最后在用戶取件之后訂單狀態(tài)更新后數(shù)據(jù)基本就不再更新了。
下單模塊:我想大部分人看過寄快遞下單流程或者自己下過單,核心就是一個表單頁面填寫寄件人姓名、地址、手機(jī)等信息和收件人姓名、地址、手機(jī)等信息。所以在這里具體實現(xiàn)也是填寫寄件人和收件人信息儲存。
物流模塊 :一個訂單下單后可能經(jīng)歷若干物流地點,最終才能到達(dá)目的地被簽收。而就各個物流點來看,各個物流點的管理人員對該物流訂單添加一些物流信息,例如到達(dá)地址、訂單目前狀態(tài)、聯(lián)系方式等等。而本案例在添加物流信息的實現(xiàn)上也通過一個表單添加該訂單的物流信息,通過物流訂單的id進(jìn)行聯(lián)立。
實現(xiàn)這種數(shù)據(jù)應(yīng)該如何存儲?如果使用關(guān)系型數(shù)據(jù)庫,就單訂單物流信息存儲可能至少需要使用兩張表來實現(xiàn),一張訂單(order)信息表存儲訂單一些固定欄位信息,一張物流(Logistics)信息表儲存動態(tài)的物流變化,通過訂單id實現(xiàn)兩張表的關(guān)聯(lián)。
按照E-R圖設(shè)計數(shù)據(jù)庫,按照我們簡潔的設(shè)計方式,其數(shù)據(jù)其中一部分的數(shù)據(jù)是這樣的:
物流表中的order_id外鍵引用order表中的id字段進(jìn)行關(guān)聯(lián)。在查詢訂單數(shù)據(jù)的時候需要關(guān)聯(lián)查詢。物流訂單系統(tǒng)確實可以使用關(guān)系數(shù)據(jù)庫去實現(xiàn),但是數(shù)據(jù)量過大可能會有性能瓶頸需要優(yōu)化,如果采用MongoDB不僅可以提高效率,還可以使得流程變得更加簡單。
訂單的特點是隨著遞送過程,訂單數(shù)據(jù)需要隨時更新路徑。數(shù)據(jù)結(jié)構(gòu)上需要可以靈活應(yīng)對,這點非常符合MongoDB的document文檔模型,并且MongoDB支持GIS功能,非常適用于MongoDB來支撐物流業(yè)務(wù)(這里簡易版本就不使用該功能了)。而物流行業(yè)里訂單比較獨立,跨訂單的操作很少,創(chuàng)建、更新(追加)的操作會較多,物流業(yè)務(wù)模型上與MongoDB非常的匹配。本課程就是使用MongoDB實現(xiàn)一個物流訂單系統(tǒng)的小例子。
1.3 案例涉及知識點
SpringBoot
相信你對SpringBoot很熟悉,由于Spring的發(fā)展、微服務(wù)的發(fā)展使得SpringBoot越來越流行,已經(jīng)成為JavaWeb開發(fā)的主流框架。
SpringBoot是由Pivotal團(tuán)隊提供的全新框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,SpringBoot在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。
簡而言之,SpringBoot是當(dāng)前web開發(fā)主流,其簡化了Spring的配置讓開發(fā)者能夠更容易上手Web項目的開發(fā)。且MongdoDB能夠快速與SpringBoot整合,在項目中能夠快速便捷操作MongoDB;
MongoDB
MongoDB是一個基于分布式文件存儲的數(shù)據(jù)庫。由C++語言編寫。旨在為web應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲解決方案。MongoDB是一個介于關(guān)系型數(shù)據(jù)庫和非關(guān)系型數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系型數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系型數(shù)據(jù)庫的。它支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似JSON的BSON格式,因此可以存儲比較復(fù)雜的數(shù)據(jù)類型。MongoDB最大的特點是它支持的查詢語言非常強(qiáng)大,其語法有點類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能,而且還支持對數(shù)據(jù)建立索引。
本案例就是基于SpringBoot和MongoDB實現(xiàn)一個物流訂單系統(tǒng)的小案例,實際的物流場景需要考慮的問題肯定很多也比較復(fù)雜,這是實現(xiàn)一個簡易版本的物流訂單系統(tǒng)主要為了MongoDB的使用和學(xué)習(xí)。
1.4案例實現(xiàn)步驟
分析完案例以及了解案例設(shè)計的知識點后,就可以一步一步開始動手實現(xiàn)本案例,本案例要實現(xiàn)的就是訂單創(chuàng)建、訂單信息更新、查詢、刪除的一個小型完整的物流訂單管理系統(tǒng)。而在具體實現(xiàn)上按照以下步驟:
- 預(yù)備工作:創(chuàng)建數(shù)據(jù)庫和項目
- 訂單添加
- 訂單更新
- 訂單查詢
- 訂單刪除
整個案例實現(xiàn)火熱運行的環(huán)境如下:
- 操作系統(tǒng):Windows10
- JDK版本:JDK8
- 編譯器:IDEA
- MongoDB版本:4.4.0
- MongoDB可視化管理工具:Studio 3T
實現(xiàn)步驟
第一步 預(yù)備工作
1.1 創(chuàng)建MongoDB數(shù)據(jù)庫
打開Studio 3T數(shù)據(jù)庫管理工具,連接本地MongoDB數(shù)據(jù)庫之后,創(chuàng)建名為test的數(shù)據(jù)庫,在test數(shù)據(jù)庫中創(chuàng)建名為order的集合:
1.2 創(chuàng)建SpringBoot項目
首先,打開IDEA創(chuàng)建項目,選擇創(chuàng)建SpringBoot項目:
然后在選擇Gruop和Aritifact的時候分別填寫com和mongodemo,Java Version選擇8版本。
在勾選模塊時候,這里勾選Spring web、MongoDB依賴模塊,選擇合適位置創(chuàng)建項目,項目就可以成功創(chuàng)建:
創(chuàng)建項目之后,需要做一些前置工作預(yù)備。
1.3 創(chuàng)建Java相關(guān)文件
創(chuàng)建完項目,我們需要做一些預(yù)備工作用來完成緩存。我們首先要在項目中的application.properties中添加配置連接到數(shù)據(jù)庫,配置規(guī)則為:spring.data.mongodb.uri=mongodb://地址:端口/數(shù)據(jù)庫名
,本案例使用本地的MongoDB數(shù)據(jù)庫,默認(rèn)端口為27017,而使用的MongoDB具體數(shù)據(jù)庫名稱為test,那么就可以按照以下進(jìn)行配置:
spring.data.mongodb.uri=mongodb://localhost:27017/test
這樣在項目中就可以連接到本地的MongoDB的test數(shù)據(jù)庫并訪問。
其次在項目中com.mongodb目錄下分別創(chuàng)建controller,service,pojo文件夾,在controller文件夾下創(chuàng)建orderController
類,為負(fù)責(zé)url和邏輯的控制器:
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); }
其中:
- @RestController就聲明該類為一個控制器,并且每個接口返回一個JSON字符串給前端。
- Logger對象用于打印日志。在web項目中我們更傾向于使用log打印日志而不在控制臺直接輸出。
orderController創(chuàng)建完畢后,在service 文件夾下創(chuàng)建orderService.java
類,里面先編寫以下內(nèi)容:
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; }
其中:
- @Service 表示該類為一個service(事務(wù)處理),可以被注入到其他對象中(Spring幫你管理)。
- @Autowired表示要注入對象的意思,下面緊接著被注入的對象。而MongoTemplate 就是已經(jīng)封裝好一個對象,一個在Spring中操作MongoDB的對象。
service創(chuàng)建完成,我們需要在pojo中創(chuàng)建logistics類和order類,分別表示具體物流信息和訂單信息。其中l(wèi)ogistics類如下,各個字段的含義請看注釋:
package com.mongodemo.pojo; import java.util.Date; public class logistics { private int orderId;//訂單id private String operation;//操作 private String operator;//操作員 @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8") private Date operationTime;//操作時間 private String address;//地址 private String details;//備注細(xì)節(jié) 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; } }
order類的內(nèi)容如下:
package com.mongodemo.pojo; import java.util.Date; import java.util.List; public class order { private int id;//訂單id private String status;//狀態(tài) @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8") private Date orderTime;//下單時間 private String shipper;//發(fā)貨人 private String shippingAdress;//發(fā)貨地址 private long shipperPhone;//發(fā)貨人手機(jī) @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8") private Date shipTime;//發(fā)貨時間 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; } //省略get set方法,自己補(bǔ)全 }
其中 @JsonFormat(pattern = “yyyy-MM-dd HH:mm”,timezone = “GMT+8”)為時間類的json輸出格式,供前端使用。
1.4 創(chuàng)建html相關(guān)文件
在static文件夾下創(chuàng)建index.html
,addlogistics.html
,addorder.html
.ordermanage.html
.
進(jìn)入layui官網(wǎng)下載layui的js和css文件。解壓后核心文件放到static下。到JQuery官網(wǎng)下載jquery-3.5.1.min.js文件,在static下創(chuàng)建js文件夾并把JQuery的js文件放進(jìn)去,最終前端的頁面會是這樣的:
其中index.html文件為后臺管理的主要ui頁面,每個小功能的頁面只需要編寫對應(yīng)頁面即可。在index.html中編寫以下內(nèi)容:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>訂單管理系統(tǒng)</title> <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > </head> <body class="layui-layout-body"> <div class="layui-layout layui-layout-admin"> <div class="layui-header"> <div class="layui-logo">ordermanage</div> <!-- 頭部區(qū)域(可配合layui已有的水平導(dǎo)航) --> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item"> <a href="javascript:;" rel="external nofollow" rel="external nofollow" > bigsai </a> </li> </ul> </div> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll"> <!-- 左側(cè)導(dǎo)航區(qū)域(可配合layui已有的垂直導(dǎo)航) --> <ul class="layui-nav layui-nav-tree" lay-filter="test"> <li class="layui-nav-item layui-nav-itemed"> <a class="" href="javascript:;" rel="external nofollow" rel="external nofollow" >訂單管理</a> <dl class="layui-nav-child"> <dd><a href="ordermanage.html" rel="external nofollow" target="container">訂單管理</a></dd> <dd><a href="addorder.html" rel="external nofollow" target="container">訂單添加</a></dd> <dd><a href="addlogistics.html" rel="external nofollow" target="container">物流添加</a></dd> </dl> </li> </ul> </div> </div> <div class="layui-body"> <!-- 內(nèi)容主體區(qū)域 --> <iframe src="addorder.html" name="container" width="100%" height="100%"></iframe> </div> <div class="layui-footer"> <!-- 底部固定區(qū)域 --> bigsai帶你學(xué) </div> </div> <script src="layui/layui.js"></script> <script src="layui/modules/jquery.js"></script> <!--<script src="layui/main.js"></script>--> <script> // JavaScript代碼區(qū)域 layui.use('element', function(){ var $ = layui.jquery ,element = layui.element; //Tab的切換功能,切換事件監(jiān)聽等,需要依賴element模塊 //觸發(fā)事件 var active = { tabAdd: function(){ //新增一個Tab項 element.tabAdd('demo', { title: '新選項'+ (Math.random()*1000|0) //用于演示 ,content: '內(nèi)容'+ (Math.random()*1000|0) ,id: new Date().getTime() //實際使用一般是規(guī)定好的id,這里以時間戳模擬下 }) } ,tabDelete: function(othis){ //刪除指定Tab項 element.tabDelete('demo', '44'); //刪除:“商品管理” othis.addClass('layui-btn-disabled'); } ,tabChange: function(){ //切換到指定Tab項 element.tabChange('demo', '22'); //切換到:用戶管理 } }; }); </script> </body> </html>
打開頁面后可以看到后臺管理的初步頁面:
左側(cè)三個菜單分別對應(yīng)創(chuàng)建的ordermanage.html,addorder.html,addlogistics.html三個頁面。至此預(yù)備工作已經(jīng)完成了,下面只需要完成具體的操作。本課程會著重講解后端和MongoDB的部分,前端知識會簡單介紹,需要深入理解還要自己多多研究。
第二步 訂單添加
下單我想誰都會,每次等待物流信息的時候是不是有一種滿滿的期待和喜悅感呢!
咱們今天帶你動手體驗這份小喜悅,完成案例后想下多少單下多少單。
2.1 后端部分
首先,在orderService編寫addorder函數(shù),用來向MongoDB中添加訂單。具體代碼如下:
//創(chuàng)建訂單,傳來order對象 public void addorder(order order) { mongoTemplate.insert(order,"order"); }
上面的代碼中:
插入的語句為 mongoTemplate.insert(order,"order")
,第一個參數(shù)為插入的文檔記錄,第二個參數(shù)"order"
為連接的MongoDB對應(yīng)數(shù)據(jù)庫下的集合(Collections)。
在orderController中編寫addorder()接口,用來處理前端的請求添加訂單。具體代碼為:
@Autowired orderService orderService; @PostMapping("addorder") public String addorder(order order) { order.setStatus("發(fā)貨中"); order.setOrderTime(new Date()); order.setShipTime(new Date()); orderService.addorder(order); return "添加成功"; }
上面代碼中:
- @Autowired注解用來注入對象,下面的 orderService orderService就是被注入的對象,注入之后不需要手動創(chuàng)建對象可以直接使用(Spring幫你管理)
- @PostMapping(“addorder”) 意為聲明一個post請求方式的接口,接口地址為addorder。
- public String addorder(order order)函數(shù)名隨意,函數(shù)的參數(shù)可以是對應(yīng)成表單的各個字段然后創(chuàng)建一個order對象,但這里直接創(chuàng)建一個order對象而前端表單傳遞對應(yīng)名稱值將直接賦值(省的再次賦值)。
- 這里為了簡單實現(xiàn),下單日期和發(fā)貨日期都為系統(tǒng)當(dāng)前時間,且訂單狀態(tài)初始默認(rèn)為發(fā)貨中。
2.2 前端部分
有了后端部分的支持,前端我們在addorder.html中編寫以下內(nèi)容,主要是一個表單向服務(wù)端發(fā)送數(shù)據(jù)和請求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > </head> <body> <section class="layui-larry-box"> <div class="larry-personal"> <blockquote class="layui-elem-quote layui-text"> <span>增加訂單</span> </blockquote> <form class="layui-form col-lg-5 " action="addorder" method="post"> <div class="layui-form-item"> <label class="layui-form-label">訂單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">發(fā)貨人姓名</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">發(fā)貨人地址</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">發(fā)貨人電話</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">收件人姓名</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">收件人地址</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">收件人手機(jī)</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">添加</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </section> </body> <script type="text/javascript" src="layui/layui.js"></script>
寫完后啟動程序訪問localhost:8080
點擊訂單添加,然后在表單中填寫對應(yīng)內(nèi)容
當(dāng)然為了測試你可以再寫一單,添加之后你會發(fā)現(xiàn)MongoDB中成功添加了訂單數(shù)據(jù),這樣下單這一步就大功告成啦!
第三步 訂單更新(追加訂單)
創(chuàng)建完訂單之后,無數(shù)配送公司和人員便開始配送物流,而我們在查詢的時候,物流狀態(tài)信息也能夠時不時的刷新,具體物流信息也能得到追加。
3.1 后端部分
在后端的處理上,我們先寫service,再寫controller,在orderService中編寫addLogisticsAndUpdateStatus()函數(shù),主要實現(xiàn)更新訂單的狀態(tài)和訂單的物流情況。具體代碼為:
//更新物流 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);//更新狀態(tài) update.push("logistics",logistics); mongoTemplate.upsert(query, update, order.class); }
其中:
- jQuery對象來輔助我們根據(jù)條件查詢待更新數(shù)據(jù),這里的意思就是查詢數(shù)據(jù)的條件為:MongoDB中_id字段為具體物流對應(yīng)的訂單id。
- Update對象用來設(shè)置更新的字段和數(shù)據(jù),其set()方法用來直接更新對應(yīng)字段的值,而push()方法用來向?qū)?yīng)數(shù)組中追加數(shù)值。因為訂單狀態(tài)需要直接更新使用set()方法,而物流信息是由多個物流數(shù)據(jù)組成,所以需要使用push()追加到記錄的后面。
- mongoTemplate.upsert(query, update, order.class)用來實現(xiàn)更新操作的提交,如果MongoDB中不存在該數(shù)據(jù)那么就插入到MongoDB中。
編寫完orderService,在orderController中編寫一個名為updateorder的接口,用來處理更新的請求和參數(shù)并執(zhí)行更新的操作,具體代碼為:
@PostMapping("updateorder") public String updateorder(logistics logistics) { logistics.setOperationTime(new Date()); orderService.addLogisticsAndUpdateStatus(logistics); return "添加成功"; }
同樣接口類型為post類型,接收部分參數(shù)然后將物流操作時間設(shè)置為當(dāng)前時間,調(diào)用orderService的addLogisticsAndUpdateStatus()方法執(zhí)行更新的操作。這樣后端部分就完成了。
3.2 前端部分
有了后端部分的支持,前端我們在addlogistics.html中編寫以下內(nèi)容,主要是一個表單向服務(wù)端發(fā)送數(shù)據(jù)和更新請求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > </head> <body> <section class="layui-larry-box"> <div class="larry-personal"> <blockquote class="layui-elem-quote layui-text"> <span>增加物流信息</span> </blockquote> <form class="layui-form col-lg-5 " action="updateorder" method="post"> <div class="layui-form-item"> <label class="layui-form-label">訂單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">操作名稱</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">操作員</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">操作地址</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">備注</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">添加</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </section> </body> <script type="text/javascript" src="layui/layui.js"></script>
這樣,前端部分編寫完成,執(zhí)行程序訪問localhost:8080
,點擊添加物流,根據(jù)1001的訂單號添加物流信息。
添加之后查看MongoDB中訂單狀態(tài)得到更新且物流數(shù)據(jù)得到更新(追加):
第四步 訂單查詢
訂單的添加和修改都完成了,非常重要的查詢當(dāng)然不能少,不僅不能少,還要特色的展示,這里查詢通過一個訂單號查詢對應(yīng)訂單的狀態(tài)和物流。
4.1 后端部分
首先在orderservice中編寫getOrderById()函數(shù),用來根據(jù)訂單id查詢該條訂單記錄。具體代碼為:
//通過id查詢物流 public order getOrderById(int id) { Query query = new Query(Criteria.where("_id").is(id)); order order=mongoTemplate.findOne(query, order.class); return order; }
其中:
- Query對象來輔助我們實現(xiàn)條件查詢待更新數(shù)據(jù),這里的意思就是查詢條件同樣為:MongoDB中_id字段為傳進(jìn)來id的該條記錄。
- 查詢一條記錄語句為:mongoTemplate.findOne(query, order.class),第一個參數(shù)為查詢的條件,第二個參數(shù)為查詢結(jié)果轉(zhuǎn)成Java對象的類型,它幫你自動處理。
- 如果查詢多條記錄即可用findAll()方法,返回的類型為List的集合類型。
寫完service然后在orderController中編寫getorderbyid接口用來處理用戶請求和參數(shù)并調(diào)用orderService的getOrderById()方法給前端返回該order對象序列化成的json字符串。具體代碼為:
@GetMapping("getorderbyid") public order getOrderById(int id) { order order=orderService.getOrderById(id); return order; }
這樣,后端部分就完成,僅需要前端渲染數(shù)據(jù)即可。
4.2 前端部分:
后端設(shè)計完成之后,需要前端來實現(xiàn),在這里使用Ajax來實現(xiàn)交互,前端頁面點擊按鈕JavaScript攜帶參數(shù)發(fā)送請求,后端查詢MongoDB后返回結(jié)果給前端渲染, 而在渲染方面為了更像物流訂單系統(tǒng),我們使用layui的 時間軸組件,將各個物流訂單數(shù)據(jù)直觀性展示。
前端在ordermanage.html中編寫以下內(nèi)容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > </head> <body> <blockquote class="layui-elem-quote layui-text"> 訂單管理 </blockquote> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label">訂單號</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()">搜索</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.min..js"></script> <script type="text/javascript"> function search() {//根據(jù) var orderid = $("#orderid").val(); $("#orderbody").html(''); $("#timezhou").html(''); $.ajax( { url:"getorderbyid", data:{ 'id':orderid }, method:'GET', success:function (order) { $("#order").html('訂單號:'+orderid+'('+order['status']+')'); $("#orderbody").append('發(fā)件人:'+order['shipper']+' 發(fā)件人手機(jī):'+order['shipperPhone']+' 發(fā)件人地址:'+order['shippingAdress']+' 下單時間:'+order['shipTime']); $("#orderbody").append('<br>收件人:'+order['recevier']+' 收獲人手機(jī):'+order['receviePhone']+' 收獲人地址:'+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-icon layui-timeline-axis"></i>\n' + ' <div class="layui-timeline-content layui-text">\n' + ' <h3 class="layui-timeline-title">'+'('+logistics[i].operation+')'+logistics[i].operationTime+ ' </h3><p>'+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' + ' </div>\n' + ' </li>'); } }, error:function (order) { layer.msg(order) } }) } </script>
其中Ajax將返回的值通過組裝渲染,將帶填充數(shù)據(jù)區(qū)域先設(shè)置id屬性,然后用JavaScript把數(shù)據(jù)渲染到該部分,核心的思路在 search() 函數(shù)中。
啟動程序,訪問localhost:8080
,點擊訂單管理,查詢訂單號為1001的物流情況。
利用上述添加物流信息,多添加該訂單的物流信息,模擬多一些流程。查詢的結(jié)果為:
第五步 訂單刪除
作為管理人員,可能偶爾會遇到特殊情況需要刪除訂單,而這種操作需求也是很有必要的,在這里實現(xiàn)根據(jù)id刪除訂單。我們在刪除訂單時候,一般先查詢訂單的一些數(shù)據(jù)和結(jié)果,然后根據(jù)查詢的id刪除對應(yīng)的記錄。
5.1 后端模塊
首先在orderService中編寫deleteOrderById()函數(shù),用來根據(jù)id刪除,編寫getAllorder()函數(shù),用來查詢所有訂單。
//根據(jù)id刪除記錄 public boolean deleteOrderById(int id) { Query query = new Query(Criteria.where("_id").is(id)); mongoTemplate.remove(query,order.class,"order"); return true; } //查詢所有訂單 public List<order>getAllorder() { List<order>list=mongoTemplate.findAll(order.class,"order"); return list; }
其中:
- 刪除的語句為 mongoTemplate.remove(query,order.class,“order”);第一個參數(shù)為待刪除記錄的定位條件,第二個參數(shù)為待刪除數(shù)據(jù)的Java類型,第三個參數(shù)為待刪除數(shù)據(jù)所在集合名稱。
- 查詢所有記錄語句為:mongoTemplate.findAll(order.class,“order”);第一個參數(shù)為查詢結(jié)果轉(zhuǎn)成Java對象的類型,它幫你自動處理。第二個參數(shù)為待查詢的集合。
寫完service,接著在orderController中編寫deletebyid接口和getallorder接口,分別用來接收處理刪除訂單的請求和獲取所有訂單的請求。
@GetMapping("deletebyid") public String deleteById(int id) { orderService.deleteOrderById(id); return "成功"; } @GetMapping("getallorders") public Map<String,Object> getAllOrder() { 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; }
其中,getallorder接口返回一個Map<String,Object>類型的數(shù)據(jù)格式,這是因為layui表格需要特定的json格式所以我們將數(shù)據(jù)存到Map中返回。啟動訪問localhost:8080/getallorders
你會看到以下格式:
5.2 前端部分
我們將前端部分同樣寫在ordermanage.html中。在這個頁面實現(xiàn)查詢訂單和管理的功能。
首先在body的div中添加表格屬性,用來表示一個表格:
<div class="larry-personal-body clearfix"> <table class="layui-hide" id="ordertable" lay-filter="ordertable"></table> </div>
在body域下側(cè)添加編輯欄的代碼,是表格附屬的一個編輯對象,刪除的按鈕就在這里。
<script type="text/html" id="toolbarDemo"> <div class="layui-btn-container"> <button class="layui-btn layui-btn-sm" lay-event="getCheckData">右側(cè)進(jìn)行篩選導(dǎo)出</button> </div> </script> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a> </script>
最后,在最底層script域添加表格渲染的代碼和Ajax發(fā)送請求的代碼:
layui.use('table', function(){ var table = layui.table;//高版本建議把括號去掉,有的低版本,需要加() table.render({ elem: '#ordertable' ,url: 'getallorders' //數(shù)據(jù)接口 ,page: false //開啟分頁 ,toolbar: '#toolbarDemo' ,cols: [[ //表頭 {field: 'id', title: 'id', sort: true, fixed: 'left',width:80} ,{field: 'orderTime', title: '下單時間',sort:true,width:80} ,{field: 'recevierAddress', title: '收貨地址'} ,{field: 'recevier', title: '收貨人' ,edit:'text'} ,{field: 'receviePhone', title: '收貨人手機(jī)' } ,{field: 'shippingAdress', title: '發(fā)貨地址'} ,{field: 'shipper', title: '發(fā)貨人'} ,{field: 'shipperPhone', title: '發(fā)貨人手機(jī)'} ,{field: 'status', title: '物流狀態(tài)'} ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150} ]] }); //頭工具欄事件 //監(jiān)聽單元格編輯 table.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("您可以直接單擊單元格進(jìn)行編輯")) } }); });
其中:
table.render為layui語法,配置數(shù)據(jù)url和格式,對應(yīng)各個字段數(shù)據(jù)名稱和含義,數(shù)據(jù)即可渲染。而表格最右側(cè)刪除需要對應(yīng)刪除的url,點擊刪除后訪問后端的deletebyid接口,將這一行數(shù)據(jù)的id發(fā)送到后端,后端的orderController接收到該請求會調(diào)用orderService的方法刪除MongoDB中對應(yīng)的數(shù)據(jù)。
具體添加的位置為:
啟動程序,訪問localhost:8080
,點擊訂單管理,看到查詢的物流訂單咱們刪除id為1001:
再查看頁面和MongoDB數(shù)據(jù)庫,你會發(fā)現(xiàn)id為1001的記錄被成功刪除:
結(jié)語
到此,MongoDB的實戰(zhàn)小項目——一個物流訂單系統(tǒng)就完成啦,我想優(yōu)秀的你肯定已經(jīng)能夠使用MongoDB “操作一頓猛如虎”!
回顧本節(jié)課程,首先是從宏觀介紹了MongoDB這個非關(guān)系型數(shù)據(jù)庫特點以及場景,從場景中選取一個比較適合的案例作為本課程案例—實現(xiàn)一個物流訂單系統(tǒng),緊接著帶你簡單分析物流訂單案例邏輯以及在關(guān)系數(shù)據(jù)庫和MongoDB中的不同處理方式,最后創(chuàng)建Springboot整合MongoDB的項目實現(xiàn)一個簡易版本的物流訂單系統(tǒng)!
當(dāng)然,本節(jié)只是帶你入門MongoDB,講了一些比較基礎(chǔ)的內(nèi)容和簡單的使用,如果需要深入學(xué)習(xí)使用MongoDB,還需要多從官網(wǎng)文檔以及其他書籍和文章更深入學(xué)習(xí)MongoDB,它是當(dāng)前非常熱門的一種基于文檔的非關(guān)系型數(shù)據(jù)庫,是一種必須掌握的技術(shù)點,望你走的更遠(yuǎn)!下課!
到此這篇關(guān)于SpringBoot+MongoDB實現(xiàn)物流訂單系統(tǒng)的代碼的文章就介紹到這了,更多相關(guān)SpringBoot+MongoDB物流訂單系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用命令方式安裝MongoDB指南(Windows、Linux)
這篇文章主要介紹了使用命令方式安裝MongoDB指南,本文分別介紹Windows、Linux下使用命令的方式安裝mongodb,需要的朋友可以參考下2015-04-04Spring Boot中使用MongoDB數(shù)據(jù)庫的方法
MongoDB是一個高性能,開源,無模式的,基于分布式文件存儲的文檔型數(shù)據(jù)庫,由C++語言編寫,其名稱來源取自“humongous”,是一種開源的文檔數(shù)據(jù)庫──NoSql數(shù)據(jù)庫的一種。這篇文章主要介紹了Spring Boot中使用MongoDB數(shù)據(jù)庫的方法,需要的朋友可以參考下2017-12-12分布式文檔存儲數(shù)據(jù)庫之MongoDB訪問控制的操作方法
這篇文章主要介紹了分布式文檔存儲數(shù)據(jù)庫之MongoDB訪問控制的操作方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11MongoDB模糊查詢操作案例詳解(類關(guān)系型數(shù)據(jù)庫的 like 和 not like)
這篇文章主要介紹了MongoDB的模糊查詢操作(類關(guān)系型數(shù)據(jù)庫的 like 和 not like) ,本文通過代碼案例分析給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,,需要的朋友可以參考下2019-07-07deepin 15.3 X64系統(tǒng)中安裝mongodb的方法步驟
這篇文章主要跟大家分享了deepin 15.3 X64系統(tǒng)中安裝mongodb的方法步驟,文中將安裝步驟介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來跟著小編一起學(xué)習(xí)學(xué)習(xí)吧。2017-04-04