SpringBoot构建电商基础秒杀项目总结-商品模块开发

Posted hequnwang10

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot构建电商基础秒杀项目总结-商品模块开发相关的知识,希望对你有一定的参考价值。

商品模块开发

一、商品创建

1、构建数据库:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for item
-- ----------------------------
DROP TABLE IF EXISTS `item`;
CREATE TABLE `item` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `price` double(10,0) NOT NULL DEFAULT '0',
  `description` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `sales` int(11) NOT NULL DEFAULT '0',
  `img_url` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


-- ----------------------------
-- Table structure for item_stock
-- ----------------------------
DROP TABLE IF EXISTS `item_stock`;
CREATE TABLE `item_stock` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stock` int(11) NOT NULL DEFAULT '0' COMMENT '库存',
  `item_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2、修改pom.xml文件

 <configuration>
       <!--允许移动生成的文件-->
       <verbose>true</verbose>
       <!--允许自动覆盖文件(生产环境中千万不要这样做)-->
       <overwrite>false</overwrite>
       <configurationFile>
         src/main/resources/mybatis-generator.xml
       </configurationFile>
</configuration>

修改mybatis-generator配置文件

 <table tableName="item" domainObjectName="ItemDO"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false"></table>
<table tableName="item_stock" domainObjectName="ItemStockDO"
       enableCountByExample="false"
       enableUpdateByExample="false"
       enableDeleteByExample="false"
       enableSelectByExample="false"
       selectByExampleQueryId="false"></table>

重新运行mybatis-generator

3、修改ItemDOMapper.xml文件

 <insert id="insert" parameterType="com.miaoshaproject.dataobject.ItemDO" useGeneratedKeys="true" keyProperty="id">
 <insert id="insertSelective" parameterType="com.miaoshaproject.dataobject.ItemDO" useGeneratedKeys="true" keyProperty="id">

4、修改ItemStockDOMapper.xml文件

  <insert id="insertSelective" parameterType="com.miaoshaproject.dataobject.ItemStockDO" useGeneratedKeys="true" keyProperty="id">

5、前端的createitem.html

<html>
<head>
  <meta charset="UTF-8">
  <link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
  <link href="static/assets/global/plugins/css/component.css" rel="stylesheet" type="text/css"/>
  <link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
  <script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
  <title>Title</title>
</head>
<body class="login">
<div class="content">
  <h3 class="form-title">创建商品</h3>
  <div class="form-group">
	<label class="control-label">商品名</label>
	<div>
		<input class="form-control" type="text" name="title" id="title">
	</div>
</div>
<div class="form-group">
	<label class="control-label">商品描述</label>
	<div>
		<input class="form-control" type="text" name="description" id="description">
	</div>
</div>
<div class="form-group">
	<label class="control-label">商品价格</label>
	<div>
		<input class="form-control" type="text" name="price" id="price">
	</div>
</div>
<div class="form-group">
	<label class="control-label">商品图片</label>
	<div>
		<input class="form-control" type="text" name="imgUrl" id="imgUrl">
	</div>
</div>
<div class="form-group">
	<label class="control-label">库存</label>
	<div>
		<input class="form-control" type="text" name="stock" id="stock">
	</div>
</div>
	<div class="form-actions">
		<button class="btn blue" id="create" type="submit">
			提交创建
		</button>
	</div>
</div>
</body>
<script>
  jQuery(document).ready(function () {
    //绑定otp的click事件用于向后端发送获取手机验证码的请求
    $("#create").on("click",function () {
     var title = $("#title").val();
	 var price = $("#price").val();
	 var stock = $("#stock").val();
	 var description = $("#description").val();
	 var imgUrl = $("#imgUrl").val();
     if (title == null || title == "") {
		alert("商品名不能为空");
		return false;
	 }
	 if (price == null || price == "") {
		alert("商品价格不能为空");
		return false;
	 }
	 if (stock == null || stock == "") {
		alert("商品库存不能为空");
		return false;
	 }
	 if (description == null || description == "") {
		alert("商品描述不能为空");
		return false;
	 }
	 if (imgUrl == null || imgUrl == "") {
		alert("商品图片不能为空");
		return false;
	 }
      //映射到后端@RequestMapping(value = "/register", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
      $.ajax({
        type:"POST",
        contentType:"application/x-www-form-urlencoded",
        url:"http://localhost:8090/item/create",
        data:{
            "title": title,
			"price": price,
			"stock": stock,
			"description": description,
			"imgUrl": imgUrl,
			"name":name
        },
        //允许跨域请求
        xhrFields:{withCredentials:true},
        success:function (data) {
          if (data.status=="success") {
            alert("创建成功");
          }else {
            alert("创建失败,原因为" + data.data.errMsg);
          }
        },
        error:function (data) {
          alert("创建失败,原因为"+data.responseText);
        }
      });
      return false;
    });
  });
</script>
</html>

二、后端商品代码

1、ItemStockDOMapper.xml文件添加语句:

  <select id="selectByItemId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from item_stock
    where item_id = #{item_id,jdbcType=INTEGER}
  </select>

ItemStockDOMapper.java

    ItemStockDO selectByItemId(Integer itemId);

2、ItemService接口

public interface ItemService {
    //创建商品
    ItemModel createItem(ItemModel itemModel);
    //商品列表浏览
    List<ItemModel> listItem();
    //商品详情浏览
    ItemModel getItemById(Integer id);
}

3、ItemServiceImpl.java实现

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ValidatorImpl validator;
    @Autowired
    private ItemDOMapper itemDOMapper;
    @Autowired
    private ItemStockDOMapper itemStockDOMapper;
    private ItemDO convertItemDOFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemDO itemDO = new ItemDO();
        BeanUtils.copyProperties(itemModel, itemDO);
        itemDO.setPrice(itemModel.getPrice().doubleValue());//视频里有
        return itemDO;
    }
    private ItemStockDO convertItemStockDOFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemStockDO itemStockDO = new ItemStockDO();
        itemStockDO.setItemId(itemModel.getId());
        itemStockDO.setStock(itemModel.getStock());

        return itemStockDO;
    }
    @Override
    @Transactional
    public ItemModel createItem(ItemModel itemModel) throws BusinessException {
        //校验入参
        ValidationResult result = validator.validate(itemModel);
        if (result.isHasErrors()){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }
        //转化itemmodel->dataobject
        ItemDO itemDO = this.convertItemDOFromItemModel(itemModel);
        //写入数据库
        itemDOMapper.insertSelective(itemDO);
        itemModel.setId(itemDO.getId());
        ItemStockDO itemStockDO = this.convertItemStockDOFromItemModel(itemModel);
        itemStockDOMapper.insertSelective(itemStockDO);
        //返回创建完成的对象
        return this.getItemById(itemModel.getId());
    }
    @Override
    public List<ItemModel> listItem() {
        return null;
    }
    @Override
    public ItemModel getItemById(Integer 

以上是关于SpringBoot构建电商基础秒杀项目总结-商品模块开发的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot构建电商基础秒杀项目总结-商品列表

SpringBoot构建电商基础秒杀项目总结

SpringBoot构建电商基础秒杀项目总结

SpringBoot构建电商基础秒杀项目总结

SpringBoot构建电商基础秒杀项目总结

SpringBoot构建电商基础秒杀项目总结-交易模块开发