課程導學
我們都知道MongoDB是一款非常出色的非關系型文檔數據庫,你肯定會想問MongoDB這么強,我們該怎么用或者有啥運用場景呢?
MongoDB的應用場景非常多,無論是數據存儲還是日志存儲越來越多的公司在使用MongoDB,而我們今天也在SpringBoot基礎上使用MongoDB實現一個簡易版本的物流訂單管理系統。
在使用前,你自己的電腦上要有IDEA編譯器來創建項目,還要擁有MongoDB數據庫和Studio 3T(MongoDB可視化數據庫管理工具,下載地址https://studio3t.com/)。
案例分析
1.1 案例分析
我想,大部分人都應該有著購物的經歷,當商品下單時就會出現一個物流單號,接下來幾天內的物流信息會根據這個單號更新。
然后接下來的幾天可能會到達不同地點,進行更新,你可能會好奇這樣一個功能是如何實現,本案例就通過SpringBoot+MongoDB實現一個簡易版本的物流訂單系統。當然具體實現商用肯定要考慮很多細節也很復雜,本案例更側重于功能實現和MongoDB使用。
1.2 核心思路拆解
一個訂單數據是如何產生和更新的呢?首先一個訂單數據由下單時產生,然后該訂單經歷各個物流點更新物流信息和訂單狀態,最后在用戶取件之后訂單狀態更新后數據基本就不再更新了。
下單模塊:我想大部分人看過寄快遞下單流程或者自己下過單,核心就是一個表單頁面填寫寄件人姓名、地址、手機等信息和收件人姓名、地址、手機等信息。所以在這里具體實現也是填寫寄件人和收件人信息儲存。
物流模塊 :一個訂單下單后可能經歷若干物流地點,最終才能到達目的地被簽收。而就各個物流點來看,各個物流點的管理人員對該物流訂單添加一些物流信息,例如到達地址、訂單目前狀態、聯系方式等等。而本案例在添加物流信息的實現上也通過一個表單添加該訂單的物流信息,通過物流訂單的id進行聯立。
實現這種數據應該如何存儲?如果使用關系型數據庫,就單訂單物流信息存儲可能至少需要使用兩張表來實現,一張訂單(order)信息表存儲訂單一些固定欄位信息,一張物流(Logistics)信息表儲存動態的物流變化,通過訂單id實現兩張表的關聯。
按照E-R圖設計數據庫,按照我們簡潔的設計方式,其數據其中一部分的數據是這樣的:
物流表中的order_id外鍵引用order表中的id字段進行關聯。在查詢訂單數據的時候需要關聯查詢。物流訂單系統確實可以使用關系數據庫去實現,但是數據量過大可能會有性能瓶頸需要優化,如果采用MongoDB不僅可以提高效率,還可以使得流程變得更加簡單。
訂單的特點是隨著遞送過程,訂單數據需要隨時更新路徑。數據結構上需要可以靈活應對,這點非常符合MongoDB的document文檔模型,并且MongoDB支持GIS功能,非常適用于MongoDB來支撐物流業務(這里簡易版本就不使用該功能了)。而物流行業里訂單比較獨立,跨訂單的操作很少,創建、更新(追加)的操作會較多,物流業務模型上與MongoDB非常的匹配。本課程就是使用MongoDB實現一個物流訂單系統的小例子。
1.3 案例涉及知識點
SpringBoot
相信你對SpringBoot很熟悉,由于Spring的發展、微服務的發展使得SpringBoot越來越流行,已經成為JavaWeb開發的主流框架。
SpringBoot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,SpringBoot在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。
簡而言之,SpringBoot是當前web開發主流,其簡化了Spring的配置讓開發者能夠更容易上手Web項目的開發。且MongdoDB能夠快速與SpringBoot整合,在項目中能夠快速便捷操作MongoDB;
MongoDB
MongoDB是一個基于分布式文件存儲的數據庫。由C++語言編寫。旨在為web應用提供可擴展的高性能數據存儲解決方案。MongoDB是一個介于關系型數據庫和非關系型數據庫之間的產品,是非關系型數據庫當中功能最豐富,最像關系型數據庫的。它支持的數據結構非常松散,是類似JSON的BSON格式,因此可以存儲比較復雜的數據類型。MongoDB最大的特點是它支持的查詢語言非常強大,其語法有點類似于面向對象的查詢語言,幾乎可以實現類似關系數據庫單表查詢的絕大部分功能,而且還支持對數據建立索引。
本案例就是基于SpringBoot和MongoDB實現一個物流訂單系統的小案例,實際的物流場景需要考慮的問題肯定很多也比較復雜,這是實現一個簡易版本的物流訂單系統主要為了MongoDB的使用和學習。
1.4案例實現步驟
分析完案例以及了解案例設計的知識點后,就可以一步一步開始動手實現本案例,本案例要實現的就是訂單創建、訂單信息更新、查詢、刪除的一個小型完整的物流訂單管理系統。而在具體實現上按照以下步驟:
- 預備工作:創建數據庫和項目
- 訂單添加
- 訂單更新
- 訂單查詢
- 訂單刪除
整個案例實現火熱運行的環境如下:
- 操作系統:Windows10
- JDK版本:JDK8
- 編譯器:IDEA
- MongoDB版本:4.4.0
- MongoDB可視化管理工具:Studio 3T
實現步驟
第一步 預備工作
1.1 創建MongoDB數據庫
打開Studio 3T數據庫管理工具,連接本地MongoDB數據庫之后,創建名為test的數據庫,在test數據庫中創建名為order的集合:
1.2 創建SpringBoot項目
首先,打開IDEA創建項目,選擇創建SpringBoot項目:
然后在選擇Gruop和Aritifact的時候分別填寫com和mongodemo,Java Version選擇8版本。
在勾選模塊時候,這里勾選Spring web、MongoDB依賴模塊,選擇合適位置創建項目,項目就可以成功創建:
創建項目之后,需要做一些前置工作預備。
1.3 創建Java相關文件
創建完項目,我們需要做一些預備工作用來完成緩存。我們首先要在項目中的application.properties中添加配置連接到數據庫,配置規則為:spring.data.mongodb.uri=mongodb://地址:端口/數據庫名
,本案例使用本地的MongoDB數據庫,默認端口為27017,而使用的MongoDB具體數據庫名稱為test,那么就可以按照以下進行配置:
1
|
spring.data.mongodb.uri=mongodb: //localhost:27017/test |
這樣在項目中就可以連接到本地的MongoDB的test數據庫并訪問。
其次在項目中com.mongodb目錄下分別創建controller,service,pojo文件夾,在controller文件夾下創建orderController
類,為負責url和邏輯的控制器:
1
2
3
4
5
6
7
8
9
10
11
|
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創建完畢后,在service 文件夾下創建orderService.java
類,里面先編寫以下內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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(事務處理),可以被注入到其他對象中(Spring幫你管理)。
- @Autowired表示要注入對象的意思,下面緊接著被注入的對象。而MongoTemplate 就是已經封裝好一個對象,一個在Spring中操作MongoDB的對象。
service創建完成,我們需要在pojo中創建logistics類和order類,分別表示具體物流信息和訂單信息。其中logistics類如下,各個字段的含義請看注釋:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
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; //備注細節 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類的內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package com.mongodemo.pojo; import java.util.Date; import java.util.List; public class order { private int id; //訂單id private String status; //狀態 @JsonFormat (pattern = "yyyy-MM-dd HH:mm" ,timezone = "GMT+8" ) private Date orderTime; //下單時間 private String shipper; //發貨人 private String shippingAdress; //發貨地址 private long shipperPhone; //發貨人手機 @JsonFormat (pattern = "yyyy-MM-dd HH:mm" ,timezone = "GMT+8" ) private Date shipTime; //發貨時間 private String recevier; //接收人 private String recevierAddress; //接收地址 private long receviePhone; //接收人號碼 private List<logistics>logistics; //物流信息 public order( int id, String status, Date orderTime, String shipper, String shippingAdress, long shipperPhone, Date shipTime, String recevier, String recevierAddress, long receviePhone, List<com.mongodemo.pojo.logistics> logistics) { this .id = id; this .status = status; this .orderTime = orderTime; this .shipper = shipper; this .shippingAdress = shippingAdress; this .shipperPhone = shipperPhone; this .shipTime = shipTime; this .recevier = recevier; this .recevierAddress = recevierAddress; this .receviePhone = receviePhone; this .logistics = logistics; } //省略get set方法,自己補全 } |
其中 @JsonFormat(pattern = “yyyy-MM-dd HH:mm”,timezone = “GMT+8”)為時間類的json輸出格式,供前端使用。
1.4 創建html相關文件
在static文件夾下創建index.html
,addlogistics.html
,addorder.html
.ordermanage.html
.
進入layui官網下載layui的js和css文件。解壓后核心文件放到static下。到JQuery官網下載jquery-3.5.1.min.js文件,在static下創建js文件夾并把JQuery的js文件放進去,最終前端的頁面會是這樣的:
其中index.html文件為后臺管理的主要ui頁面,每個小功能的頁面只需要編寫對應頁面即可。在index.html中編寫以下內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
<!DOCTYPE html> <html> <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1, maximum-scale=1" > <title>訂單管理系統</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> <!-- 頭部區域(可配合layui已有的水平導航) --> <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" > <!-- 左側導航區域(可配合layui已有的垂直導航) --> <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" > <!-- 內容主體區域 --> <iframe src= "addorder.html" name= "container" width= "100%" height= "100%" ></iframe> </div> <div class= "layui-footer" > <!-- 底部固定區域 --> bigsai帶你學 </div> </div> <script src= "layui/layui.js" ></script> <script src= "layui/modules/jquery.js" ></script> <!--<script src= "layui/main.js" ></script>--> <script> // JavaScript代碼區域 layui.use( 'element' , function (){ var $ = layui.jquery ,element = layui.element; //Tab的切換功能,切換事件監聽等,需要依賴element模塊 //觸發事件 var active = { tabAdd: function (){ //新增一個Tab項 element.tabAdd( 'demo' , { title: '新選項' + (Math.random()*1000|0) //用于演示 ,content: '內容' + (Math.random()*1000|0) ,id: new Date().getTime() //實際使用一般是規定好的id,這里以時間戳模擬下 }) } ,tabDelete: function (othis){ //刪除指定Tab項 element.tabDelete( 'demo' , '44' ); //刪除:“商品管理” othis.addClass( 'layui-btn-disabled' ); } ,tabChange: function (){ //切換到指定Tab項 element.tabChange( 'demo' , '22' ); //切換到:用戶管理 } }; }); </script> </body> </html> |
打開頁面后可以看到后臺管理的初步頁面:
左側三個菜單分別對應創建的ordermanage.html,addorder.html,addlogistics.html三個頁面。至此預備工作已經完成了,下面只需要完成具體的操作。本課程會著重講解后端和MongoDB的部分,前端知識會簡單介紹,需要深入理解還要自己多多研究。
第二步 訂單添加
下單我想誰都會,每次等待物流信息的時候是不是有一種滿滿的期待和喜悅感呢!
咱們今天帶你動手體驗這份小喜悅,完成案例后想下多少單下多少單。
2.1 后端部分
首先,在orderService編寫addorder函數,用來向MongoDB中添加訂單。具體代碼如下:
1
2
3
4
5
|
//創建訂單,傳來order對象 public void addorder(order order) { mongoTemplate.insert(order, "order" ); } |
上面的代碼中:
插入的語句為 mongoTemplate.insert(order,"order")
,第一個參數為插入的文檔記錄,第二個參數"order"
為連接的MongoDB對應數據庫下的集合(Collections)。
在orderController中編寫addorder()接口,用來處理前端的請求添加訂單。具體代碼為:
1
2
3
4
5
6
7
8
9
10
11
|
@Autowired orderService orderService; @PostMapping ( "addorder" ) public String addorder(order order) { order.setStatus( "發貨中" ); order.setOrderTime( new Date()); order.setShipTime( new Date()); orderService.addorder(order); return "添加成功" ; } |
上面代碼中:
- @Autowired注解用來注入對象,下面的 orderService orderService就是被注入的對象,注入之后不需要手動創建對象可以直接使用(Spring幫你管理)
- @PostMapping(“addorder”) 意為聲明一個post請求方式的接口,接口地址為addorder。
- public String addorder(order order)函數名隨意,函數的參數可以是對應成表單的各個字段然后創建一個order對象,但這里直接創建一個order對象而前端表單傳遞對應名稱值將直接賦值(省的再次賦值)。
- 這里為了簡單實現,下單日期和發貨日期都為系統當前時間,且訂單狀態初始默認為發貨中。
2.2 前端部分
有了后端部分的支持,前端我們在addorder.html中編寫以下內容,主要是一個表單向服務端發送數據和請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
<!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" >發貨人姓名</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" >發貨人地址</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" >發貨人電話</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" >收件人手機</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
點擊訂單添加,然后在表單中填寫對應內容
當然為了測試你可以再寫一單,添加之后你會發現MongoDB中成功添加了訂單數據,這樣下單這一步就大功告成啦!
第三步 訂單更新(追加訂單)
創建完訂單之后,無數配送公司和人員便開始配送物流,而我們在查詢的時候,物流狀態信息也能夠時不時的刷新,具體物流信息也能得到追加。
3.1 后端部分
在后端的處理上,我們先寫service,再寫controller,在orderService中編寫addLogisticsAndUpdateStatus()函數,主要實現更新訂單的狀態和訂單的物流情況。具體代碼為:
1
2
3
4
5
6
7
8
9
10
|
//更新物流 public void addLogisticsAndUpdateStatus(logistics logistics) { String status=logistics.getOperation(); Query query = new Query(Criteria.where( "_id" ).is(logistics.getOrderId())); Update update = new Update(); update.set( "status" , status); //更新狀態 update.push( "logistics" ,logistics); mongoTemplate.upsert(query, update, order. class ); } |
其中:
- jQuery對象來輔助我們根據條件查詢待更新數據,這里的意思就是查詢數據的條件為:MongoDB中_id字段為具體物流對應的訂單id。
- Update對象用來設置更新的字段和數據,其set()方法用來直接更新對應字段的值,而push()方法用來向對應數組中追加數值。因為訂單狀態需要直接更新使用set()方法,而物流信息是由多個物流數據組成,所以需要使用push()追加到記錄的后面。
- mongoTemplate.upsert(query, update, order.class)用來實現更新操作的提交,如果MongoDB中不存在該數據那么就插入到MongoDB中。
編寫完orderService,在orderController中編寫一個名為updateorder的接口,用來處理更新的請求和參數并執行更新的操作,具體代碼為:
1
2
3
4
5
6
7
|
@PostMapping ( "updateorder" ) public String updateorder(logistics logistics) { logistics.setOperationTime( new Date()); orderService.addLogisticsAndUpdateStatus(logistics); return "添加成功" ; } |
同樣接口類型為post類型,接收部分參數然后將物流操作時間設置為當前時間,調用orderService的addLogisticsAndUpdateStatus()方法執行更新的操作。這樣后端部分就完成了。
3.2 前端部分
有了后端部分的支持,前端我們在addlogistics.html中編寫以下內容,主要是一個表單向服務端發送數據和更新請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<!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> |
這樣,前端部分編寫完成,執行程序訪問localhost:8080
,點擊添加物流,根據1001的訂單號添加物流信息。
添加之后查看MongoDB中訂單狀態得到更新且物流數據得到更新(追加):
第四步 訂單查詢
訂單的添加和修改都完成了,非常重要的查詢當然不能少,不僅不能少,還要特色的展示,這里查詢通過一個訂單號查詢對應訂單的狀態和物流。
4.1 后端部分
首先在orderservice中編寫getOrderById()函數,用來根據訂單id查詢該條訂單記錄。具體代碼為:
1
2
3
4
5
6
7
|
//通過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對象來輔助我們實現條件查詢待更新數據,這里的意思就是查詢條件同樣為:MongoDB中_id字段為傳進來id的該條記錄。
- 查詢一條記錄語句為:mongoTemplate.findOne(query, order.class),第一個參數為查詢的條件,第二個參數為查詢結果轉成Java對象的類型,它幫你自動處理。
- 如果查詢多條記錄即可用findAll()方法,返回的類型為List的集合類型。
寫完service然后在orderController中編寫getorderbyid接口用來處理用戶請求和參數并調用orderService的getOrderById()方法給前端返回該order對象序列化成的json字符串。具體代碼為:
1
2
3
4
5
6
|
@GetMapping( "getorderbyid" ) public order getOrderById(int id) { order order=orderService.getOrderById(id); return order; } |
這樣,后端部分就完成,僅需要前端渲染數據即可。
4.2 前端部分:
后端設計完成之后,需要前端來實現,在這里使用Ajax來實現交互,前端頁面點擊按鈕JavaScript攜帶參數發送請求,后端查詢MongoDB后返回結果給前端渲染, 而在渲染方面為了更像物流訂單系統,我們使用layui的 時間軸組件,將各個物流訂單數據直觀性展示。
前端在ordermanage.html中編寫以下內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
<!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() { //根據 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( '發件人:' +order[ 'shipper' ]+ ' 發件人手機:' +order[ 'shipperPhone' ]+ ' 發件人地址:' +order[ 'shippingAdress' ]+ ' 下單時間:' +order[ 'shipTime' ]); $( "#orderbody" ).append( '<br>收件人:' +order[ 'recevier' ]+ ' 收獲人手機:' +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將返回的值通過組裝渲染,將帶填充數據區域先設置id屬性,然后用JavaScript把數據渲染到該部分,核心的思路在 search() 函數中。
啟動程序,訪問localhost:8080
,點擊訂單管理,查詢訂單號為1001的物流情況。
利用上述添加物流信息,多添加該訂單的物流信息,模擬多一些流程。查詢的結果為:
第五步 訂單刪除
作為管理人員,可能偶爾會遇到特殊情況需要刪除訂單,而這種操作需求也是很有必要的,在這里實現根據id刪除訂單。我們在刪除訂單時候,一般先查詢訂單的一些數據和結果,然后根據查詢的id刪除對應的記錄。
5.1 后端模塊
首先在orderService中編寫deleteOrderById()函數,用來根據id刪除,編寫getAllorder()函數,用來查詢所有訂單。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//根據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”);第一個參數為待刪除記錄的定位條件,第二個參數為待刪除數據的Java類型,第三個參數為待刪除數據所在集合名稱。
- 查詢所有記錄語句為:mongoTemplate.findAll(order.class,“order”);第一個參數為查詢結果轉成Java對象的類型,它幫你自動處理。第二個參數為待查詢的集合。
寫完service,接著在orderController中編寫deletebyid接口和getallorder接口,分別用來接收處理刪除訂單的請求和獲取所有訂單的請求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@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>類型的數據格式,這是因為layui表格需要特定的json格式所以我們將數據存到Map中返回。啟動訪問localhost:8080/getallorders
你會看到以下格式:
5.2 前端部分
我們將前端部分同樣寫在ordermanage.html中。在這個頁面實現查詢訂單和管理的功能。
首先在body的div中添加表格屬性,用來表示一個表格:
1
2
3
|
<div class= "larry-personal-body clearfix" > <table class= "layui-hide" id= "ordertable" lay-filter= "ordertable" ></table> </div> |
在body域下側添加編輯欄的代碼,是表格附屬的一個編輯對象,刪除的按鈕就在這里。
1
2
3
4
5
6
7
8
9
|
<script type= "text/html" id= "toolbarDemo" > <div class= "layui-btn-container" > <button class= "layui-btn layui-btn-sm" lay-event= "getCheckData" >右側進行篩選導出</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發送請求的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
layui.use( 'table' , function (){ var table = layui.table; //高版本建議把括號去掉,有的低版本,需要加() table.render({ elem: '#ordertable' ,url: 'getallorders' //數據接口 ,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: '收貨人手機' } ,{field: 'shippingAdress' , title: '發貨地址' } ,{field: 'shipper' , title: '發貨人' } ,{field: 'shipperPhone' , title: '發貨人手機' } ,{field: 'status' , title: '物流狀態' } ,{fixed: 'right' , title: '操作' , toolbar: '#barDemo' , width:150} ]] }); //頭工具欄事件 //監聽單元格編輯 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( "您可以直接單擊單元格進行編輯" )) } }); }); |
其中:
table.render為layui語法,配置數據url和格式,對應各個字段數據名稱和含義,數據即可渲染。而表格最右側刪除需要對應刪除的url,點擊刪除后訪問后端的deletebyid接口,將這一行數據的id發送到后端,后端的orderController接收到該請求會調用orderService的方法刪除MongoDB中對應的數據。
具體添加的位置為:
啟動程序,訪問localhost:8080
,點擊訂單管理,看到查詢的物流訂單咱們刪除id為1001:
再查看頁面和MongoDB數據庫,你會發現id為1001的記錄被成功刪除:
結語
到此,MongoDB的實戰小項目——一個物流訂單系統就完成啦,我想優秀的你肯定已經能夠使用MongoDB “操作一頓猛如虎”!
回顧本節課程,首先是從宏觀介紹了MongoDB這個非關系型數據庫特點以及場景,從場景中選取一個比較適合的案例作為本課程案例—實現一個物流訂單系統,緊接著帶你簡單分析物流訂單案例邏輯以及在關系數據庫和MongoDB中的不同處理方式,最后創建Springboot整合MongoDB的項目實現一個簡易版本的物流訂單系統!
當然,本節只是帶你入門MongoDB,講了一些比較基礎的內容和簡單的使用,如果需要深入學習使用MongoDB,還需要多從官網文檔以及其他書籍和文章更深入學習MongoDB,它是當前非常熱門的一種基于文檔的非關系型數據庫,是一種必須掌握的技術點,望你走的更遠!下課!
到此這篇關于SpringBoot+MongoDB實現物流訂單系統的代碼的文章就介紹到這了,更多相關SpringBoot+MongoDB物流訂單系統內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_40693171/article/details/108229145