SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

贾藻
• 阅读 1261

业务描述

基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现商品模块的增删改查操作。

项目环境初始化

准备工作

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

数据库初始化

打开mysql控制台,然后按如下步骤执行goods.sql文件。
第一步:登录mysql。

mysql –uroot –proot

第二步:设置控制台编码方式。

set names utf8;

第三步:执行goods.sql文件(切记不要打开文件复制到mysql客户端运行)。

source d:/goods.sql

其中goods.sql文件内容如下:

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());

或者利用navicat软件将goods.sql导入mysql数据库

创建项目并添加依赖

第一步:基于start.spring.io 创建项目并设置基本信息
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

第二步:创建项目时指定项目核心依赖
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能
第三步:项目创建以后分析其结构
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

项目配置文件内容初始化

#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架构设计,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品查询业务实现

业务描述

从商品库查询商品信息,并将商品信息呈现在页面上,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品查询时序分析

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

Pojo类定义

定义Goods对象,用于封装从数据库查询到的商品信息。

package com.cy.pj.goods.pojo;
import java.util.Date;
public class Goods {
    private Integer 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 Integer getId() {
        return id;
    }
    public void setId(Integer 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();
}

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();
}

oodsService接口实现类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();
     }
}

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
    }
    
}

基于Thymeleaf模板引擎实现数据呈现

在templates/pages目录中添加goods.html页面,并在body中添加如下元素:

<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页面上数据呈现分析:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

启动Tomcat进行访问测试分析

首先,启动tomcat,然后在打开浏览器,在地址栏输入访问地址,获取服务端数据并进行呈现,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

项目运行过程中的BUG分析

  • 控制台“?”符号,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 数据库连不上,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 服务启动失败,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • SQL语法问题,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 日期格式不正确,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 页面上${}内容错误,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 页面日期格式不正确,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 依赖注入失败,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 空指针异常(NullPointerException),如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品删除业务实现

业务描述

从商品库查询商品信息后,点击页面上删除超链接,基于id删除当前行记录,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

业务时序分析

在商品呈现页面,用户执行删除操作,其删除时序如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

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页面中添加删除超链接,接Goods.html,查询:

<td><a href="#" th:href="@{/goods/doUpdate/{id}(id=${g.id})}">update</a></td>

Thymeleaf 官方th:href应用说明,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

删除操作中,客户端与服务端代码关联说明,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

启动tomcat服务器进行访问测试分析

首先,启动tomcat,然后在打开浏览器,在地址栏输入访问地址,获取服务端数据并进行呈现,接下来点击页面上的删除按钮,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

删除成功以后,的页面如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

项目启动及运行过程中的Bug及问题分析

  • SQL映射元素定义问题,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 客户端请求参数与服务端参数不匹配,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品添加业务实现

业务描述

在Goods列表页面,添加添加按钮,进行添加页面,然后在添加页面输入商品相关信息,然后保存到数据库,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品添加页面,设计如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

业务时序分析

在商品添加页面,输入商品信息,然后提交到服务端进行保存,其时序分析如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

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类中添加用于返回商品添加页面的方法,代码如下:

    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...),出现如下界面,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

第三步:在添加页面中填写表单,然后点击save按钮将表单数据提交到服务端,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能
第四步:添加页面中表单数据提交过程分析,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

项目启动及运行过程中的Bug及问题分析

  • 客户端显示400异常,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 保存时500异常,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 数据库完整性约束异常,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

商品修改业务实现

业务描述

在商品列表页面,点击update选项,基于商品id查询当前行记录然后将其更新到goods-update页面,如图所示:
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能
在update页面选中,修改商品信息,然后点击 update goods 将表单数据提交到服务端进行更新

修改业务时序设计

基于id查询商品信息的时序设计
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能
将goods-update页面中的数据提交到服务端进行更新的时序设计
SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

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添加页面设计及实现

在goods.html页面中<table>添加修改超链接:

<td><a href="#" th:href="@{/goods/doUpdate/{id}(id=${g.id})}">update</a></td>

在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服务,访问商品列表页面,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

在列表页面,点击update选项,进入更新页面

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

在更新页面更新表单数据,然后提交,进入列表页面查看更新结果,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

业务构建及运行时的Bug分析

  • 页面设计分析,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

  • 页面源码分析,如图所示:

SpringBoot+MyBatis+Spring 技术整合实现商品模块的CRUD功能

总结

重点讲解了SpringBoot工程下MyBatis,SpringMVC,Thymeleaf技术的综合应用,重点理解其业务实现过程以及问题的解决过程。

点赞
收藏
评论区
推荐文章
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Easter79 Easter79
4年前
springboot与安全
概念:安全SpringSecurity是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅需引入springbootstartersecurity模块,进行少量的配置,即可实现强大的安全管理。几个类:    WebSec
Easter79 Easter79
4年前
SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
1.前言本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例。使用技术:SpringBoot、mybatis、shiro、thymeleaf、pagehelper、Mapper插件、druid、dataTables、ztree、jQuery开发工具:intellijidea数据库:mys
Easter79 Easter79
4年前
SSM_基于传统web项目
1.这是一个单模块的项目!有四个配置文件,mybaits,spring。springmvc,web.xml!2.web.xml配置文件,导入spring和springmvc的配置文件,spring配置文件中,获取sqlsession,以及关联mybatis的mpper(增删改查)文件3.mybatis的配置文件则可以不用写
Stella981 Stella981
4年前
SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
1.前言本文主要介绍使用SpringBoot与shiro实现基于数据库的细粒度动态权限管理系统实例。使用技术:SpringBoot、mybatis、shiro、thymeleaf、pagehelper、Mapper插件、druid、dataTables、ztree、jQuery开发工具:intellijidea数据库:mys
Stella981 Stella981
4年前
SSM_基于传统web项目
1.这是一个单模块的项目!有四个配置文件,mybaits,spring。springmvc,web.xml!2.web.xml配置文件,导入spring和springmvc的配置文件,spring配置文件中,获取sqlsession,以及关联mybatis的mpper(增删改查)文件3.mybatis的配置文件则可以不用写
鸿蒙小林 鸿蒙小林
7个月前
《仿盒马》app开发技术分享-- 首页商品流(7)
技术栈Appgalleryconnect开发准备上一节我们实现了首页banner模块的功能,现在我们的首页还需要添加商品列表,作为一个购物类应用,商品列表是非常重要的一个模块,所以我们尽量把它设计的足够完善,参数能更好的支持我们后期复杂的逻辑,它需要有图片
鸿蒙小林 鸿蒙小林
7个月前
《仿盒马》app开发技术分享-- 分类模块顶部导航列表(15)
技术栈Appgalleryconnect开发准备上一节我们实现了购物车商品列表的大部分功能,实现了商品的添加、删除、增减、价格计算等业务,并且都跟云端进行通信。现在我们继续对项目进行改造,这一节我们要改造的内容是分类页,这个页面我们在之前的非端云一体化项目
linbojue linbojue
2星期前
Java通用型支付+电商平台双系统实战 | 完结
掌握基础增删改查(CRUD)只是Java开发的起点,要真正吃透这门技术栈,必须深入业务场景,通过实际项目来磨练架构思维。本文将围绕“电商”与“支付”这两个强关联的核心系统,从技术选型、架构设计到核心代码实现,带你一步步完成从初级开发向架构设计的进阶。一、项