SpringBoot+MongoDB實(shí)現(xiàn)物流訂單系統(tǒng)的代碼
課程導(dǎo)學(xué)
我們都知道MongoDB是一款非常出色的非關(guān)系型文檔數(shù)據(jù)庫(kù),你肯定會(huì)想問MongoDB這么強(qiáng),我們?cè)撛趺从没蛘哂猩哆\(yùn)用場(chǎng)景呢?
MongoDB的應(yīng)用場(chǎng)景非常多,無論是數(shù)據(jù)存儲(chǔ)還是日志存儲(chǔ)越來越多的公司在使用MongoDB,而我們今天也在SpringBoot基礎(chǔ)上使用MongoDB實(shí)現(xiàn)一個(gè)簡(jiǎn)易版本的物流訂單管理系統(tǒng)。
在使用前,你自己的電腦上要有IDEA編譯器來創(chuàng)建項(xiàng)目,還要擁有MongoDB數(shù)據(jù)庫(kù)和Studio 3T(MongoDB可視化數(shù)據(jù)庫(kù)管理工具,下載地址https://studio3t.com/)。
案例分析
1.1 案例分析
我想,大部分人都應(yīng)該有著購(gòu)物的經(jīng)歷,當(dāng)商品下單時(shí)就會(huì)出現(xiàn)一個(gè)物流單號(hào),接下來幾天內(nèi)的物流信息會(huì)根據(jù)這個(gè)單號(hào)更新。
然后接下來的幾天可能會(huì)到達(dá)不同地點(diǎn),進(jìn)行更新,你可能會(huì)好奇這樣一個(gè)功能是如何實(shí)現(xiàn),本案例就通過SpringBoot+MongoDB實(shí)現(xiàn)一個(gè)簡(jiǎn)易版本的物流訂單系統(tǒng)。當(dāng)然具體實(shí)現(xiàn)商用肯定要考慮很多細(xì)節(jié)也很復(fù)雜,本案例更側(cè)重于功能實(shí)現(xiàn)和MongoDB使用。
1.2 核心思路拆解
一個(gè)訂單數(shù)據(jù)是如何產(chǎn)生和更新的呢?首先一個(gè)訂單數(shù)據(jù)由下單時(shí)產(chǎn)生,然后該訂單經(jīng)歷各個(gè)物流點(diǎn)更新物流信息和訂單狀態(tài),最后在用戶取件之后訂單狀態(tài)更新后數(shù)據(jù)基本就不再更新了。
下單模塊:我想大部分人看過寄快遞下單流程或者自己下過單,核心就是一個(gè)表單頁面填寫寄件人姓名、地址、手機(jī)等信息和收件人姓名、地址、手機(jī)等信息。所以在這里具體實(shí)現(xiàn)也是填寫寄件人和收件人信息儲(chǔ)存。
物流模塊 :一個(gè)訂單下單后可能經(jīng)歷若干物流地點(diǎn),最終才能到達(dá)目的地被簽收。而就各個(gè)物流點(diǎn)來看,各個(gè)物流點(diǎn)的管理人員對(duì)該物流訂單添加一些物流信息,例如到達(dá)地址、訂單目前狀態(tài)、聯(lián)系方式等等。而本案例在添加物流信息的實(shí)現(xiàn)上也通過一個(gè)表單添加該訂單的物流信息,通過物流訂單的id進(jìn)行聯(lián)立。
實(shí)現(xiàn)這種數(shù)據(jù)應(yīng)該如何存儲(chǔ)?如果使用關(guān)系型數(shù)據(jù)庫(kù),就單訂單物流信息存儲(chǔ)可能至少需要使用兩張表來實(shí)現(xiàn),一張訂單(order)信息表存儲(chǔ)訂單一些固定欄位信息,一張物流(Logistics)信息表儲(chǔ)存動(dòng)態(tài)的物流變化,通過訂單id實(shí)現(xiàn)兩張表的關(guān)聯(lián)。
按照E-R圖設(shè)計(jì)數(shù)據(jù)庫(kù),按照我們簡(jiǎn)潔的設(shè)計(jì)方式,其數(shù)據(jù)其中一部分的數(shù)據(jù)是這樣的:
物流表中的order_id外鍵引用order表中的id字段進(jìn)行關(guān)聯(lián)。在查詢訂單數(shù)據(jù)的時(shí)候需要關(guān)聯(lián)查詢。物流訂單系統(tǒng)確實(shí)可以使用關(guān)系數(shù)據(jù)庫(kù)去實(shí)現(xiàn),但是數(shù)據(jù)量過大可能會(huì)有性能瓶頸需要優(yōu)化,如果采用MongoDB不僅可以提高效率,還可以使得流程變得更加簡(jiǎn)單。
訂單的特點(diǎn)是隨著遞送過程,訂單數(shù)據(jù)需要隨時(shí)更新路徑。數(shù)據(jù)結(jié)構(gòu)上需要可以靈活應(yīng)對(duì),這點(diǎn)非常符合MongoDB的document文檔模型,并且MongoDB支持GIS功能,非常適用于MongoDB來支撐物流業(yè)務(wù)(這里簡(jiǎn)易版本就不使用該功能了)。而物流行業(yè)里訂單比較獨(dú)立,跨訂單的操作很少,創(chuàng)建、更新(追加)的操作會(huì)較多,物流業(yè)務(wù)模型上與MongoDB非常的匹配。本課程就是使用MongoDB實(shí)現(xiàn)一個(gè)物流訂單系統(tǒng)的小例子。
1.3 案例涉及知識(shí)點(diǎn)
SpringBoot
相信你對(duì)SpringBoot很熟悉,由于Spring的發(fā)展、微服務(wù)的發(fā)展使得SpringBoot越來越流行,已經(jīng)成為JavaWeb開發(fā)的主流框架。
SpringBoot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,SpringBoot在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。
簡(jiǎn)而言之,SpringBoot是當(dāng)前web開發(fā)主流,其簡(jiǎn)化了Spring的配置讓開發(fā)者能夠更容易上手Web項(xiàng)目的開發(fā)。且MongdoDB能夠快速與SpringBoot整合,在項(xiàng)目中能夠快速便捷操作MongoDB;
MongoDB
MongoDB是一個(gè)基于分布式文件存儲(chǔ)的數(shù)據(jù)庫(kù)。由C++語言編寫。旨在為web應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。MongoDB是一個(gè)介于關(guān)系型數(shù)據(jù)庫(kù)和非關(guān)系型數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系型數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系型數(shù)據(jù)庫(kù)的。它支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似JSON的BSON格式,因此可以存儲(chǔ)比較復(fù)雜的數(shù)據(jù)類型。MongoDB最大的特點(diǎn)是它支持的查詢語言非常強(qiáng)大,其語法有點(diǎn)類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實(shí)現(xiàn)類似關(guān)系數(shù)據(jù)庫(kù)單表查詢的絕大部分功能,而且還支持對(duì)數(shù)據(jù)建立索引。
本案例就是基于SpringBoot和MongoDB實(shí)現(xiàn)一個(gè)物流訂單系統(tǒng)的小案例,實(shí)際的物流場(chǎng)景需要考慮的問題肯定很多也比較復(fù)雜,這是實(shí)現(xiàn)一個(gè)簡(jiǎn)易版本的物流訂單系統(tǒng)主要為了MongoDB的使用和學(xué)習(xí)。
1.4案例實(shí)現(xiàn)步驟
分析完案例以及了解案例設(shè)計(jì)的知識(shí)點(diǎn)后,就可以一步一步開始動(dòng)手實(shí)現(xiàn)本案例,本案例要實(shí)現(xiàn)的就是訂單創(chuàng)建、訂單信息更新、查詢、刪除的一個(gè)小型完整的物流訂單管理系統(tǒng)。而在具體實(shí)現(xiàn)上按照以下步驟:
- 預(yù)備工作:創(chuàng)建數(shù)據(jù)庫(kù)和項(xiàng)目
- 訂單添加
- 訂單更新
- 訂單查詢
- 訂單刪除
整個(gè)案例實(shí)現(xiàn)火熱運(yùn)行的環(huán)境如下:
- 操作系統(tǒng):Windows10
- JDK版本:JDK8
- 編譯器:IDEA
- MongoDB版本:4.4.0
- MongoDB可視化管理工具:Studio 3T
實(shí)現(xiàn)步驟
第一步 預(yù)備工作
1.1 創(chuàng)建MongoDB數(shù)據(jù)庫(kù)
打開Studio 3T數(shù)據(jù)庫(kù)管理工具,連接本地MongoDB數(shù)據(jù)庫(kù)之后,創(chuàng)建名為test的數(shù)據(jù)庫(kù),在test數(shù)據(jù)庫(kù)中創(chuàng)建名為order的集合:
1.2 創(chuàng)建SpringBoot項(xiàng)目
首先,打開IDEA創(chuàng)建項(xiàng)目,選擇創(chuàng)建SpringBoot項(xiàng)目:
然后在選擇Gruop和Aritifact的時(shí)候分別填寫com和mongodemo,Java Version選擇8版本。
在勾選模塊時(shí)候,這里勾選Spring web、MongoDB依賴模塊,選擇合適位置創(chuàng)建項(xiàng)目,項(xiàng)目就可以成功創(chuàng)建:
創(chuàng)建項(xiàng)目之后,需要做一些前置工作預(yù)備。
1.3 創(chuàng)建Java相關(guān)文件
創(chuàng)建完項(xiàng)目,我們需要做一些預(yù)備工作用來完成緩存。我們首先要在項(xiàng)目中的application.properties中添加配置連接到數(shù)據(jù)庫(kù),配置規(guī)則為:spring.data.mongodb.uri=mongodb://地址:端口/數(shù)據(jù)庫(kù)名
,本案例使用本地的MongoDB數(shù)據(jù)庫(kù),默認(rèn)端口為27017,而使用的MongoDB具體數(shù)據(jù)庫(kù)名稱為test,那么就可以按照以下進(jìn)行配置:
spring.data.mongodb.uri=mongodb://localhost:27017/test
這樣在項(xiàng)目中就可以連接到本地的MongoDB的test數(shù)據(jù)庫(kù)并訪問。
其次在項(xiàng)目中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就聲明該類為一個(gè)控制器,并且每個(gè)接口返回一個(gè)JSON字符串給前端。
- Logger對(duì)象用于打印日志。在web項(xiàng)目中我們更傾向于使用log打印日志而不在控制臺(tái)直接輸出。
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 表示該類為一個(gè)service(事務(wù)處理),可以被注入到其他對(duì)象中(Spring幫你管理)。
- @Autowired表示要注入對(duì)象的意思,下面緊接著被注入的對(duì)象。而MongoTemplate 就是已經(jīng)封裝好一個(gè)對(duì)象,一個(gè)在Spring中操作MongoDB的對(duì)象。
service創(chuàng)建完成,我們需要在pojo中創(chuàng)建logistics類和order類,分別表示具體物流信息和訂單信息。其中l(wèi)ogistics類如下,各個(gè)字段的含義請(qǐng)看注釋:
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;//操作時(shí)間 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;//下單時(shí)間 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ā)貨時(shí)間 private String recevier;//接收人 private String recevierAddress;//接收地址 private long receviePhone;//接收人號(hào)碼 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”)為時(shí)間類的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)去,最終前端的頁面會(huì)是這樣的:
其中index.html文件為后臺(tái)管理的主要ui頁面,每個(gè)小功能的頁面只需要編寫對(duì)應(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(){ //新增一個(gè)Tab項(xiàng) element.tabAdd('demo', { title: '新選項(xiàng)'+ (Math.random()*1000|0) //用于演示 ,content: '內(nèi)容'+ (Math.random()*1000|0) ,id: new Date().getTime() //實(shí)際使用一般是規(guī)定好的id,這里以時(shí)間戳模擬下 }) } ,tabDelete: function(othis){ //刪除指定Tab項(xiàng) element.tabDelete('demo', '44'); //刪除:“商品管理” othis.addClass('layui-btn-disabled'); } ,tabChange: function(){ //切換到指定Tab項(xiàng) element.tabChange('demo', '22'); //切換到:用戶管理 } }; }); </script> </body> </html>
打開頁面后可以看到后臺(tái)管理的初步頁面:
左側(cè)三個(gè)菜單分別對(duì)應(yīng)創(chuàng)建的ordermanage.html,addorder.html,addlogistics.html三個(gè)頁面。至此預(yù)備工作已經(jīng)完成了,下面只需要完成具體的操作。本課程會(huì)著重講解后端和MongoDB的部分,前端知識(shí)會(huì)簡(jiǎn)單介紹,需要深入理解還要自己多多研究。
第二步 訂單添加
下單我想誰都會(huì),每次等待物流信息的時(shí)候是不是有一種滿滿的期待和喜悅感呢!
咱們今天帶你動(dòng)手體驗(yàn)這份小喜悅,完成案例后想下多少單下多少單。
2.1 后端部分
首先,在orderService編寫addorder函數(shù),用來向MongoDB中添加訂單。具體代碼如下:
//創(chuàng)建訂單,傳來order對(duì)象 public void addorder(order order) { mongoTemplate.insert(order,"order"); }
上面的代碼中:
插入的語句為 mongoTemplate.insert(order,"order")
,第一個(gè)參數(shù)為插入的文檔記錄,第二個(gè)參數(shù)"order"
為連接的MongoDB對(duì)應(yīng)數(shù)據(jù)庫(kù)下的集合(Collections)。
在orderController中編寫addorder()接口,用來處理前端的請(qǐng)求添加訂單。具體代碼為:
@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注解用來注入對(duì)象,下面的 orderService orderService就是被注入的對(duì)象,注入之后不需要手動(dòng)創(chuàng)建對(duì)象可以直接使用(Spring幫你管理)
- @PostMapping(“addorder”) 意為聲明一個(gè)post請(qǐng)求方式的接口,接口地址為addorder。
- public String addorder(order order)函數(shù)名隨意,函數(shù)的參數(shù)可以是對(duì)應(yīng)成表單的各個(gè)字段然后創(chuàng)建一個(gè)order對(duì)象,但這里直接創(chuàng)建一個(gè)order對(duì)象而前端表單傳遞對(duì)應(yīng)名稱值將直接賦值(省的再次賦值)。
- 這里為了簡(jiǎn)單實(shí)現(xiàn),下單日期和發(fā)貨日期都為系統(tǒng)當(dāng)前時(shí)間,且訂單狀態(tài)初始默認(rèn)為發(fā)貨中。
2.2 前端部分
有了后端部分的支持,前端我們?cè)赼ddorder.html中編寫以下內(nèi)容,主要是一個(gè)表單向服務(wù)端發(fā)送數(shù)據(jù)和請(qǐng)求:
<!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>
寫完后啟動(dòng)程序訪問localhost:8080
點(diǎn)擊訂單添加,然后在表單中填寫對(duì)應(yīng)內(nèi)容
當(dāng)然為了測(cè)試你可以再寫一單,添加之后你會(huì)發(fā)現(xiàn)MongoDB中成功添加了訂單數(shù)據(jù),這樣下單這一步就大功告成啦!
第三步 訂單更新(追加訂單)
創(chuàng)建完訂單之后,無數(shù)配送公司和人員便開始配送物流,而我們?cè)诓樵兊臅r(shí)候,物流狀態(tài)信息也能夠時(shí)不時(shí)的刷新,具體物流信息也能得到追加。
3.1 后端部分
在后端的處理上,我們先寫service,再寫controller,在orderService中編寫addLogisticsAndUpdateStatus()函數(shù),主要實(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對(duì)象來輔助我們根據(jù)條件查詢待更新數(shù)據(jù),這里的意思就是查詢數(shù)據(jù)的條件為:MongoDB中_id字段為具體物流對(duì)應(yīng)的訂單id。
- Update對(duì)象用來設(shè)置更新的字段和數(shù)據(jù),其set()方法用來直接更新對(duì)應(yīng)字段的值,而push()方法用來向?qū)?yīng)數(shù)組中追加數(shù)值。因?yàn)橛唵螤顟B(tài)需要直接更新使用set()方法,而物流信息是由多個(gè)物流數(shù)據(jù)組成,所以需要使用push()追加到記錄的后面。
- mongoTemplate.upsert(query, update, order.class)用來實(shí)現(xiàn)更新操作的提交,如果MongoDB中不存在該數(shù)據(jù)那么就插入到MongoDB中。
編寫完orderService,在orderController中編寫一個(gè)名為updateorder的接口,用來處理更新的請(qǐng)求和參數(shù)并執(zhí)行更新的操作,具體代碼為:
@PostMapping("updateorder") public String updateorder(logistics logistics) { logistics.setOperationTime(new Date()); orderService.addLogisticsAndUpdateStatus(logistics); return "添加成功"; }
同樣接口類型為post類型,接收部分參數(shù)然后將物流操作時(shí)間設(shè)置為當(dāng)前時(shí)間,調(diào)用orderService的addLogisticsAndUpdateStatus()方法執(zhí)行更新的操作。這樣后端部分就完成了。
3.2 前端部分
有了后端部分的支持,前端我們?cè)赼ddlogistics.html中編寫以下內(nèi)容,主要是一個(gè)表單向服務(wù)端發(fā)送數(shù)據(jù)和更新請(qǐng)求:
<!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
,點(diǎn)擊添加物流,根據(jù)1001的訂單號(hào)添加物流信息。
添加之后查看MongoDB中訂單狀態(tài)得到更新且物流數(shù)據(jù)得到更新(追加):
第四步 訂單查詢
訂單的添加和修改都完成了,非常重要的查詢當(dāng)然不能少,不僅不能少,還要特色的展示,這里查詢通過一個(gè)訂單號(hào)查詢對(duì)應(yīng)訂單的狀態(tài)和物流。
4.1 后端部分
首先在orderservice中編寫getOrderById()函數(shù),用來根據(jù)訂單id查詢?cè)摋l訂單記錄。具體代碼為:
//通過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對(duì)象來輔助我們實(shí)現(xiàn)條件查詢待更新數(shù)據(jù),這里的意思就是查詢條件同樣為:MongoDB中_id字段為傳進(jìn)來id的該條記錄。
- 查詢一條記錄語句為:mongoTemplate.findOne(query, order.class),第一個(gè)參數(shù)為查詢的條件,第二個(gè)參數(shù)為查詢結(jié)果轉(zhuǎn)成Java對(duì)象的類型,它幫你自動(dòng)處理。
- 如果查詢多條記錄即可用findAll()方法,返回的類型為L(zhǎng)ist的集合類型。
寫完service然后在orderController中編寫getorderbyid接口用來處理用戶請(qǐng)求和參數(shù)并調(diào)用orderService的getOrderById()方法給前端返回該order對(duì)象序列化成的json字符串。具體代碼為:
@GetMapping("getorderbyid") public order getOrderById(int id) { order order=orderService.getOrderById(id); return order; }
這樣,后端部分就完成,僅需要前端渲染數(shù)據(jù)即可。
4.2 前端部分:
后端設(shè)計(jì)完成之后,需要前端來實(shí)現(xiàn),在這里使用Ajax來實(shí)現(xiàn)交互,前端頁面點(diǎn)擊按鈕JavaScript攜帶參數(shù)發(fā)送請(qǐng)求,后端查詢MongoDB后返回結(jié)果給前端渲染, 而在渲染方面為了更像物流訂單系統(tǒng),我們使用layui的 時(shí)間軸組件,將各個(gè)物流訂單數(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">訂單號(hào)</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('訂單號(hào):'+orderid+'('+order['status']+')'); $("#orderbody").append('發(fā)件人:'+order['shipper']+' 發(fā)件人手機(jī):'+order['shipperPhone']+' 發(fā)件人地址:'+order['shippingAdress']+' 下單時(shí)間:'+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ù)中。
啟動(dòng)程序,訪問localhost:8080
,點(diǎn)擊訂單管理,查詢訂單號(hào)為1001的物流情況。
利用上述添加物流信息,多添加該訂單的物流信息,模擬多一些流程。查詢的結(jié)果為:
第五步 訂單刪除
作為管理人員,可能偶爾會(huì)遇到特殊情況需要?jiǎng)h除訂單,而這種操作需求也是很有必要的,在這里實(shí)現(xiàn)根據(jù)id刪除訂單。我們?cè)趧h除訂單時(shí)候,一般先查詢訂單的一些數(shù)據(jù)和結(jié)果,然后根據(jù)查詢的id刪除對(duì)應(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”);第一個(gè)參數(shù)為待刪除記錄的定位條件,第二個(gè)參數(shù)為待刪除數(shù)據(jù)的Java類型,第三個(gè)參數(shù)為待刪除數(shù)據(jù)所在集合名稱。
- 查詢所有記錄語句為:mongoTemplate.findAll(order.class,“order”);第一個(gè)參數(shù)為查詢結(jié)果轉(zhuǎn)成Java對(duì)象的類型,它幫你自動(dòng)處理。第二個(gè)參數(shù)為待查詢的集合。
寫完service,接著在orderController中編寫deletebyid接口和getallorder接口,分別用來接收處理刪除訂單的請(qǐng)求和獲取所有訂單的請(qǐng)求。
@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接口返回一個(gè)Map<String,Object>類型的數(shù)據(jù)格式,這是因?yàn)閘ayui表格需要特定的json格式所以我們將數(shù)據(jù)存到Map中返回。啟動(dòng)訪問localhost:8080/getallorders
你會(huì)看到以下格式:
5.2 前端部分
我們將前端部分同樣寫在ordermanage.html中。在這個(gè)頁面實(shí)現(xiàn)查詢訂單和管理的功能。
首先在body的div中添加表格屬性,用來表示一個(gè)表格:
<div class="larry-personal-body clearfix"> <table class="layui-hide" id="ordertable" lay-filter="ordertable"></table> </div>
在body域下側(cè)添加編輯欄的代碼,是表格附屬的一個(gè)編輯對(duì)象,刪除的按鈕就在這里。
<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ā)送請(qǐng)求的代碼:
layui.use('table', function(){ var table = layui.table;//高版本建議把括號(hào)去掉,有的低版本,需要加() 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: '下單時(shí)間',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和格式,對(duì)應(yīng)各個(gè)字段數(shù)據(jù)名稱和含義,數(shù)據(jù)即可渲染。而表格最右側(cè)刪除需要對(duì)應(yīng)刪除的url,點(diǎn)擊刪除后訪問后端的deletebyid接口,將這一行數(shù)據(jù)的id發(fā)送到后端,后端的orderController接收到該請(qǐng)求會(huì)調(diào)用orderService的方法刪除MongoDB中對(duì)應(yīng)的數(shù)據(jù)。
具體添加的位置為:
啟動(dòng)程序,訪問localhost:8080
,點(diǎn)擊訂單管理,看到查詢的物流訂單咱們刪除id為1001:
再查看頁面和MongoDB數(shù)據(jù)庫(kù),你會(huì)發(fā)現(xiàn)id為1001的記錄被成功刪除:
結(jié)語
到此,MongoDB的實(shí)戰(zhàn)小項(xiàng)目——一個(gè)物流訂單系統(tǒng)就完成啦,我想優(yōu)秀的你肯定已經(jīng)能夠使用MongoDB “操作一頓猛如虎”!
回顧本節(jié)課程,首先是從宏觀介紹了MongoDB這個(gè)非關(guān)系型數(shù)據(jù)庫(kù)特點(diǎn)以及場(chǎng)景,從場(chǎng)景中選取一個(gè)比較適合的案例作為本課程案例—實(shí)現(xiàn)一個(gè)物流訂單系統(tǒng),緊接著帶你簡(jiǎn)單分析物流訂單案例邏輯以及在關(guān)系數(shù)據(jù)庫(kù)和MongoDB中的不同處理方式,最后創(chuàng)建Springboot整合MongoDB的項(xiàng)目實(shí)現(xiàn)一個(gè)簡(jiǎn)易版本的物流訂單系統(tǒng)!
當(dāng)然,本節(jié)只是帶你入門MongoDB,講了一些比較基礎(chǔ)的內(nèi)容和簡(jiǎn)單的使用,如果需要深入學(xué)習(xí)使用MongoDB,還需要多從官網(wǎng)文檔以及其他書籍和文章更深入學(xué)習(xí)MongoDB,它是當(dāng)前非常熱門的一種基于文檔的非關(guān)系型數(shù)據(jù)庫(kù),是一種必須掌握的技術(shù)點(diǎn),望你走的更遠(yuǎn)!下課!
到此這篇關(guān)于SpringBoot+MongoDB實(shí)現(xiàn)物流訂單系統(tǒng)的代碼的文章就介紹到這了,更多相關(guān)SpringBoot+MongoDB物流訂單系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用命令方式安裝MongoDB指南(Windows、Linux)
這篇文章主要介紹了使用命令方式安裝MongoDB指南,本文分別介紹Windows、Linux下使用命令的方式安裝mongodb,需要的朋友可以參考下2015-04-04Spring Boot中使用MongoDB數(shù)據(jù)庫(kù)的方法
MongoDB是一個(gè)高性能,開源,無模式的,基于分布式文件存儲(chǔ)的文檔型數(shù)據(jù)庫(kù),由C++語言編寫,其名稱來源取自“humongous”,是一種開源的文檔數(shù)據(jù)庫(kù)──NoSql數(shù)據(jù)庫(kù)的一種。這篇文章主要介紹了Spring Boot中使用MongoDB數(shù)據(jù)庫(kù)的方法,需要的朋友可以參考下2017-12-12分布式文檔存儲(chǔ)數(shù)據(jù)庫(kù)之MongoDB訪問控制的操作方法
這篇文章主要介紹了分布式文檔存儲(chǔ)數(shù)據(jù)庫(kù)之MongoDB訪問控制的操作方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11mongoDB重裝或升級(jí)版本后,啟動(dòng)失敗原因及解決方法
這篇文章主要為大家分享一下重裝mongodb或者升級(jí)mongdb版本后,重啟啟動(dòng)也沒有任何錯(cuò)誤提示,但是查看為失敗failed狀態(tài),沒有啟動(dòng)成功問題的解決方法2024-05-05MongoDB模糊查詢操作案例詳解(類關(guān)系型數(shù)據(jù)庫(kù)的 like 和 not like)
這篇文章主要介紹了MongoDB的模糊查詢操作(類關(guān)系型數(shù)據(jù)庫(kù)的 like 和 not like) ,本文通過代碼案例分析給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,,需要的朋友可以參考下2019-07-07deepin 15.3 X64系統(tǒng)中安裝mongodb的方法步驟
這篇文章主要跟大家分享了deepin 15.3 X64系統(tǒng)中安裝mongodb的方法步驟,文中將安裝步驟介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來跟著小編一起學(xué)習(xí)學(xué)習(xí)吧。2017-04-04