SpringBoot+MyBatis+Spring 技術整合實現商品模塊的CRUD操做(詳細)

業務描述

基於Spring,MyBatis,SpringBoot,Thymeleaf技術實現商品模塊的增刪改查操做。css

項目環境初始化

準備工做

1. MySQL(5.7)
2. JDK (1.8)
3. Maven (3.6.3)
4. STS(4.7.1)

數據庫初始化

打開mysql控制檯,而後按以下步驟執行goods.sql文件。
第一步:登陸mysql。html

mysql –uroot –proot

第二步:設置控制檯編碼方式。java

set names utf8;

第三步:執行goods.sql文件(切記不要打開文件複製到mysql客戶端運行)。mysql

source d:/goods.sql

其中goods.sql文件內容以下:web

drop database if exists dbgoods;
create database dbgoods default character set utf8;
use dbgoods;
create table tb_goods(
     id bigint primary key auto_increment,
     name varchar(100) not null,
     remark text,
     createdTime datetime not null
)engine=InnoDB;
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());

建立項目並添加依賴

基於STS建立

第一步:基於start.spring.io 建立項目並設置基本信息spring

image.png

第二步:建立項目時指定項目核心依賴sql

image.png

第三步:項目建立之後分析其結構數據庫

image.png

基於IDEA建立

第一步:基於start.spring.io 建立項目並設置基本信息apache

image.png

image.png
第二步:建立項目module時指定項目核心依賴segmentfault

image.png

第三步:項目modul建立之後分析其結構

image.png

image.png

項目配置文件內容初始化

#server
server.port=80
#server.servlet.context-path=/
#spring datasource
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

#spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml

#spring logging
logging.level.com.cy=debug

#spring thymeleaf
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

項目API架構設計

其API架構設計,如圖所示:

image.png

商品查詢業務實現

業務描述

從商品庫查詢商品信息,並將商品信息呈如今頁面上,如圖所示:

image.png

業務時序分析

查詢全部商品信息,其業務時序分析,如圖所示:
image.png

Pojo類定義

定義Goods對象,用於封裝從數據庫查詢到的商品信息。

package com.cy.pj.goods.pojo;
import java.util.Date;
public class Goods {
    private Long id;//id bigint primary key auto_increment
    private String name;//name varchar(100) not null
    private String remark;//remark text
    private Date createdTime;//createdTime datetime
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Date getCreatedTime() {
        return createdTime;
    }
    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }
    @Override
    public String toString() {
        return "Goods [id=" + id + ", name=" + name + ",   
        remark=" + remark + ", createdTime=" + createdTime + "]";
    }
}

Dao接口方法及映射定義

在GoodsDao接口中定義商品查詢方法以及SQL映射,基於此方法及SQL映射獲取全部商品信息。代碼以下:

package com.cy.pj.goods.dao;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.cy.pj.goods.pojo.Goods;

@Mapper
public interface GoodsDao {
      @Select("select * from tb_goods")
      List<Goods> findGoods();
}

編寫單元測試類進行測試分析:

package com.cy.pj.goods.dao;
import com.cy.pj.goods.pojo.Goods;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class GoodsDaoTests {
    @Autowired
 private GoodsDao goodsDao;
    @Test
 void testFindGoods(){
        List<Goods> goodsList=goodsDao.findGoods();
        for(Goods g:goodsList){
            System.out.println(g);
        }
    }
}

測試結果問題分析

  • 數據庫連不上,如圖所示:

image.png

  • 鏈接數據庫的url 配置問題,如圖所示:

image.png

  • Sql映射重複定義問題,如圖所示:

image.png

  • 空指針問題,如圖所示:

image.png

  • SQL語法問題,如圖所示:

image.png

Service接口方法定義及實現

GoodsService接口及商品查詢方法定義

package com.cy.pj.goods.service;
import java.util.List;
import com.cy.pj.goods.pojo.Goods;
public interface GoodsService {
      List<Goods> findGoods();
}

GoodsService接口實現類GoodsServiceImpl定義及方法實現

package com.cy.pj.goods.service;
import java.util.List;
import com.cy.pj.goods.pojo.Goods;
@Service
public class GoodsServiceImpl implements GoodsService {
     @Autowired
     private GoodsDao goodsDao;
     @Override
     public List<Goods> findGoods(){
         return goodsDao.findGoods();
     }
}

編寫單元測試類進行測試分析

package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class GoodsServiceTests {
    @Autowired
 private GoodsService goodsService;
    @Test
 void testFindGoods(){
        List<Goods> goodsList=goodsService.findGoods();
        //斷言測試法(單元測試中經常使用的一種方式)
 Assertions.assertEquals(true, goodsList.size()>0);
    }
}

測試結果問題分析

  • 依賴注入問題,如圖所示:

image.png

Controller對象方法定義及實現

定義GoodsController類,並添加doGoodsUI方法,添加查詢商品信息代碼,並將查詢到的商品信息存儲到model,並返回goods頁面。

package com.cy.pj.goods.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
@Controller //@Service,@Component
@RequestMapping("/goods/")
public class GoodsController {
    //has a+di
    @Autowired
    private GoodsService goodsService;
    @RequestMapping("doGoodsUI")
    public String doGoodsUI(Model model) {
         //調用業務層方法獲取商品信息
         List<Goods> list= goodsService.findGoods();
         //將數據存儲到請求做用域
         model.addAttribute("list", list);
         return "goods";//viewname
    }
    
}

Goods商品列表頁面設計及實現

在templates/pages目錄中添加goods.html頁面,並在body中添加html元素,在運行內部使用thymeleaf標籤屬性獲取數據,代碼以下:

<table width="50%">
        <thead>
           <th>id</th>
           <th>name</th>
           <th>remark</th>
           <th>createdTime</th>
           <th>operation</th>
        </thead>
        <tbody>
           <tr th:each="g:${list}">
             <td th:text="${g.id}">1</td>
             <td th:text="${g.name}">MySQL</td>
             <td th:text="${g.remark}">DBMS</td>
             <td th:text="${#dates.format(g.createdTime, 'yyyy/MM/dd HH:mm')}">2020/07/03</td>
             <td><a>delete</a></td>
           </tr>
        </tbody>
  </table>
thymeleaf 是一種模板引擎,此引擎以html爲模板,能夠添加自定義標籤屬性,能夠將服務端model中數據填充在頁面上,而後實現與用於交互。其官網爲thymeleaf.org

Goods頁面上數據呈現分析:

image.png

啓動Tomcat進行訪問測試分析

首先,啓動tomcat,而後在打開瀏覽器,在地址欄輸入訪問地址,獲取服務端數據並進行呈現,如圖所示:
image.png

項目啓動及運行過程當中BUG及問題分析

  • STS控制檯「?」符號,如圖所示:

image.png

  • 服務啓動失敗,如圖所示:

image.png

  • 模板不存在錯誤,如圖所示:

image.png

  • 日期格式不正確,如圖所示:

image.png

  • 頁面上${}內容錯誤,如圖所示:

image.png

  • 頁面日期格式不正確,如圖所示:

image.png

  • 依賴注入失敗,如圖所示:

image.png

  • 空指針異常(NullPointerException),如圖所示:

image.png

商品刪除業務實現

業務描述

從商品庫查詢商品信息後,點擊頁面上刪除超連接,基於id刪除當前行記錄,如圖所示:

image.png

業務時序分析

在商品呈現頁面,用戶執行刪除操做,其刪除時序如圖所示:

image.png

Dao接口方法及映射定義

在GoodsDao接口中定義商品刪除方法以及SQL映射,代碼以下:

@Delete("delete from tb_goods where id=#{id}")

 int deleteById(Integer id);

Service接口方法定義及實現

在GoodsService接口中添加刪除方法,代碼以下:

int deleteById(Integer id);

在GoodsService的實現類GoodsServiceImpl中添加deleteById方法實現。代碼以下。

@Override
    public int deleteById(Integer id) {
        long t1=System.currentTimeMillis();
        int rows=goodsDao.deleteById(id);
        long t2=System.currentTimeMillis();
        System.out.println("execute time:"+(t2-t1));
        return rows;
    }

Controller對象方法定義及實現

在GoodsController中的添加doDeleteById方法,代碼以下:

@RequestMapping("doDeleteById/{id}")
    public String doDeleteById(@PathVariable Integer id){
        goodsService.deleteById(id);
        return "redirect:/goods/doGoodsUI";
    }

說明:Restful 風格爲一種軟件架構編碼風格,定義了一種url的格式,其url語法爲/a/b/{c}/{d},在這樣的語法結構中{}爲一個變量表達式。假如咱們但願在方法參數中獲取rest url中變量表達式的值,能夠使用@PathVariable註解對參數進行描述。

Goods頁面上刪除超連接定義

在goods.html頁面中添加刪除超連接,如圖所示:

image.png

Thymeleaf 官方th:href應用說明,如圖所示:

image.png

刪除操做中,客戶端與服務端代碼關聯說明,如圖所示:

image.png

啓動tomcat服務器進行訪問測試分析

首先,啓動tomcat,而後在打開瀏覽器,在地址欄輸入訪問地址,獲取服務端數據並進行呈現,接下來點擊頁面上的刪除按鈕,如圖所示:

image.png

刪除成功之後,的頁面如圖所示:

image.png

項目啓動及運行過程當中的Bug及問題分析

  • SQL映射元素定義問題,如圖所示:

image.png

  • 客戶端請求參數與服務端參數不匹配,如圖所示:

image.png

商品添加業務實現

業務描述

在Goods列表頁面,添加添加按鈕,進行添加頁面,而後在添加頁面輸入商品相關信息,而後保存到數據庫,如圖所示:

image.png

商品添加頁面,設計如圖所示:

image.png

業務時序分析

在商品添加頁面,輸入商品信息,而後提交到服務端進行保存,其時序分析如圖所示:
image.png

Dao接口方法及映射定義

在GoodsDao中添加用於保存商品信息的接口方法以及SQL映射,代碼以下:

@Insert("insert into tb_goods(name,remark,createdTime) 
values (#{name},#{remark},now())")
int insertObject(Goods entity);

說明:當SQL語句比較複雜時,也能夠將SQL定義到映射文件(xml文件)中。

Service接口方法定義及實現

在GoodsService接口中添加業務方法,用於實現商品信息添加,代碼以下:

int saveGoods(Goods entity);

在GoodsSerivceImpl類中添加接口方法實現,代碼以下:

@Override
    public int saveGoods(Goods entity) {
        int rows=goodsDao.insertObject(entity);
        return rows;
    }

Controller對象方法定義及實現

在GoodsController類中添加用於處理商品添加請求的方法,代碼以下:

@RequestMapping("doSaveGoods")
public String doSaveGoods(Goods entity) {
        goodsService.saveGoods(entity);
        return "redirect:/goods/doGoodsUI";
}

在GoodsController類中添加用於返回商品添加頁面的方法,代碼以下:

@RequestMapping("doGoodsAddUI")
    public String doGoodsAddUI() {
        return "goods-add";
    }

Goods添加頁面設計及實現

在templates的pages目錄中添加goods-add.html頁面,代碼以下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css"> ul li {list-style-type: none;} </style>
</head>
<body>
<h1>The Goods Add Page</h1>
<form th:action="@{/goods/doSaveGoods}" method="post">
   <ul>
      <li>name:
      <li><input type="text" name="name">
      <li>remark:
      <li><textarea rows="5" cols="50" name="remark"></textarea>
      <li><input type="submit" value="Save">
   </ul>
</form>
</body>
</html>

在goods.html頁面中添加,超連接能夠跳轉到添加頁面,關鍵代碼以下:

<a th:href="@{/goods/doGoodsAddUI}">添加商品</a>

啓動Tomcat服務器進行訪問測試分析

第一步:啓動web服務器,檢測啓動過程是否OK,假如沒有問題進入下一步。
第二步:打開瀏覽器在地址裏輸入http://localhost/goods/doGood...),出現以下界面,如圖所示:
image.png

第三步:在添加頁面中填寫表單,而後點擊save按鈕將表單數據提交到服務端,如圖所示:
image.png
第四步:添加頁面中表單數據提交過程分析,如圖所示:
image.png

項目啓動及運行過程當中的Bug及問題分析

  • 客戶端顯示400異常,如圖所示:

image.png

  • 保存時500異常,如圖所示:

image.png

  • 數據庫完整性約束異常,如圖所示:

image.png

商品修改業務實現

業務描述

在商品列表頁面,點擊update選項,基於商品id查詢當前行記錄而後將其更新到goods-update頁面,如圖所示:
image.png
在update頁面選中,修改商品信息,而後點擊 update goods 將表單數據提交到服務端進行更新

業務時序分析

基於id查詢商品信息的時序設計
image.png
將goods-update頁面中的數據提交到服務端進行更新的時序設計
image.png

Dao接口方法及映射定義

在GoodsDao中添加基於id查詢商品信息的方法及SQL映射,代碼以下:

@Select("select * from tb_goods where id=#{id}")
Goods findById(Integer id);

在GoodsDao中添加基於id執行Goods商品更新的方法及SQL映射,代碼以下:

@Update("update tb_goods set name=#{name},remark=#{remark} where id=#{id}")
 int updateGoods(Goods goods);

Service接口方法定義及實現

在GoodsService 中添加基於id查詢商品信息和更新商品信息的方法,代碼以下:

Goods findById(Integer id);
int updateGoods(Goods goods);

在GoodsServiceImpl中基於id查詢商品信息和更新商品信息的方法,代碼以下:

@Override
    public Goods findById(Integer id) {
        //.....
        return goodsDao.findById(id);
    }
@Override
    public int updateGoods(Goods goods) {
        return goodsDao.updateGoods(goods);
    }

Controller對象方法定義及實現

在GoodsController中添加基於id查詢商品信息的方法,代碼以下:

@RequestMapping("doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model) {
        Goods goods=goodsService.findById(id);
        model.addAttribute("goods",goods);
        return "goods-update";
    }

在GoodsController中添加更新商品信息的方法,代碼以下:

@RequestMapping("doUpdateGoods")
    public String doUpdateGoods(Goods goods) {
        goodsService.updateGoods(goods);
        return "redirect:/goods/doGoodsUI";
    }

Goods修改頁面設計及實現

在templates目錄中添加goods-update.html頁面,代碼設計以下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css"> ul li {list-style-type: none} </style>
</head>
<body>
   <h1>The Goods Update Page</h1>
   <form th:action="@{/goods/doUpdateGoods}" method="post">
      <input type="hidden" name="id" th:value="${goods.id}">
      <ul>
        <li>name:
        <li><input type="text" name="name" th:value="${goods.name}">
        <li>remark:
        <li><textarea rows="3" cols="30" name="remark" th:text="${goods.remark}"></textarea>
        <li><input type="submit" value="Update Goods">
       </ul>
   </form>
</body>
</html>

啓動Tomcat服務進行訪問測試分析

啓動tomcat服務,訪問商品列表頁面,如圖所示:

image.png

在列表頁面,點擊update選項,進入更新頁面

image.png

在更新頁面更新表單數據,而後提交,進入列表頁面查看更新結果,如圖所示:

image.png

項目啓動及運行過程當中的BUG及問題分析

  • 頁面設計分析,如圖所示:

image.png

  • 頁面源碼分析,如圖所示:

image.png

相關文章
相關標籤/搜索