首页 > 编程语言 > 详细

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

时间:2020-12-09 15:16:11      阅读:21      评论:0      收藏:0      [点我收藏+]

数据库初始化

mysql –uroot –proot
set names utf8;
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());
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());

 

创建module,添加Spring web、thymeleaf、Spring Data JDBC、MyBatis Framework、MySQL Driver

 

项目配置文件内容初始化

#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架构设计,如图所示:

技术分享图片

 

 

业务时序分析

查询所有商品信息,其业务时序分析,如图所示:

技术分享图片

 

 

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

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

 

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页面上数据呈现分析:

技术分享图片

 

技术分享图片

 

 

删除业务实现

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注解对参数进行描述。

 

添加业务

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页面中添加,超链接可以跳转到添加页面,关键代码如下:

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

修改业务

 

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>

 

 
 

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

原文:https://www.cnblogs.com/liang-shi/p/14107957.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!