程序员社区

【校园商铺SSM-18】商品类别批量添加--Dao+Service+Controller+View层的实现

文章目录

      • 1. Dao层的实现
        • 1. ProductCategoryDao接口
        • 2. ProductCategoryDao.xml实现类
        • 3. ProductCategoryDao实现类
      • 2. 结果状态标识类
        • 2.1 ProductCategoryStateEnum类
        • 2.2 Dto之ProductCategoryExecution类
        • 2.3 ProductCategoryOperationException类
      • 3. Service层的实现
        • 3.1 ProductCategoryService接口
        • 3.2 ProductCategoryServiceImpl实现类
      • 4. Controller层的实现
      • 5. View层的实现

1. Dao层的实现

1. ProductCategoryDao接口

   /**
     * 批量新增商品类别
     * @param productCategoryList
     * @return
     */
    int batchInsertProductCategory(List<ProductCategory> productCategoryList);

2. ProductCategoryDao.xml实现类

<!--批量添加商品类别-->
<insert id="batchInsertProductCategory" parameterType="java.util.List">
    insert into tb_product_category(
        product_category_name,
        priority,
        create_time,
        shop_id)
    values
        <foreach collection="list" item="productCategory" index="index" separator=",">
        (
            #{productCategory.productCategoryName},
            #{productCategory.priority},
            #{productCategory.createTime},
            #{productCategory.shopId}
        )
        </foreach>
</insert>

3. ProductCategoryDao实现类

    @Test
    public void testABatchInsertProductCategory(){
        ProductCategory productCategory = new ProductCategory();
        productCategory.setProductCategoryName("商品类别1");
        productCategory.setPriority(1);
        productCategory.setCreateTime(new Date());
        productCategory.setShopId(143L);
        ProductCategory productCategory2 = new ProductCategory();
        productCategory2.setProductCategoryName("商品类别2");
        productCategory2.setPriority(2);
        productCategory2.setCreateTime(new Date());
        productCategory2.setShopId(143L);

        List<ProductCategory> productCategoryList = new ArrayList<>();
        productCategoryList.add(productCategory);
        productCategoryList.add(productCategory2);
        int effectedNum =
                productCategoryDao.batchInsertProductCategory(productCategoryList);
        assertEquals(2,effectedNum);
    }

2. 结果状态标识类

2.1 ProductCategoryStateEnum类

package com.imooc.o2o.enums;

public enum ProductCategoryStateEnum {
    SUCCESS(1, "创建成功"),
    INNER_ERROR(-1001, "操作失败"),
    EMPTY_LIST(-1002, "添加数少于1");

    private int state ;
    private String stateInfo;

    private ProductCategoryStateEnum(int state, String stateInfo) {
        this.state = state;
        this.stateInfo = stateInfo;
    }

    public int getState() {
        return state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

    public static ProductCategoryStateEnum stateOf(int index) {
        for (ProductCategoryStateEnum productCategoryStateEnum : values()) {
            if (productCategoryStateEnum.getState() == index) {
                return productCategoryStateEnum;
            }
        }
        return null;
    }
}

2.2 Dto之ProductCategoryExecution类

在dto下面添加ProductCategoryExecution

import com.imooc.o2o.entity.ProductCategory;
import com.imooc.o2o.enums.ProductCategoryStateEnum;

import java.util.List;

public class ProductCategoryExecution {
    //结果状态
    private int state;
    //状态标识
    private String stateInfo;
    private List<ProductCategory> productCategoryList;

    public ProductCategoryExecution() {
    }

    //操作失败的时候使用的构造器(返回状态和状态值)
    public ProductCategoryExecution(ProductCategoryStateEnum stateEnum) {
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
    }

    //操作成功时的构造器
    public ProductCategoryExecution(ProductCategoryStateEnum stateEnum,
                                    List<ProductCategory> productCategoryList){
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
        this.productCategoryList = productCategoryList;
    }


    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

    public void setStateInfo(String stateInfo) {
        this.stateInfo = stateInfo;
    }

    public List<ProductCategory> getProductCategoryList() {
        return productCategoryList;
    }

    public void setProductCategoryList(List<ProductCategory> productCategoryList) {
        this.productCategoryList = productCategoryList;
    }
}

2.3 ProductCategoryOperationException类

public class ProductCategoryOperationException extends RuntimeException {
    public ProductCategoryOperationException(String msg) {
        super(msg);
    }
}

3. Service层的实现

3.1 ProductCategoryService接口

    /**
     * 批量添加商品类别 
     * @param productCategoryList
     * @return
     * @throws ProductCategoryOperationException
     */
    ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
            throws ProductCategoryOperationException;

3.2 ProductCategoryServiceImpl实现类

@Override
public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
        throws ProductCategoryOperationException {
    if(productCategoryList!=null && productCategoryList.size()>0){
        try {
            int effectedNum
                    = productCategoryDao.batchInsertProductCategory(productCategoryList);
            if(effectedNum<0){
                throw new ProductCategoryOperationException("店铺类别创建失败");
            }else {
                return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
            }
        } catch (Exception e) {
            throw new ProductCategoryOperationException("batchAddProductCategory error"+e.getMessage());
        }
    }else {
        return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
    }
}

4. Controller层的实现

@ResponseBody
@RequestMapping(value = "/addproductcategory",method = RequestMethod.POST)
private Map<String,Object> AddProductCategory(
        @RequestBody List<ProductCategory> productCategoryList,  //使用注解从前端传过来的数据
        HttpServletRequest request){
    Map<String,Object> modelMap = new HashMap<>();
    //从session中获取shopId
    Shop currentShop = (Shop)request.getSession().getAttribute("currentShop");
    for(ProductCategory pc:productCategoryList){
        pc.setShopId(currentShop.getShopId());
    }
    if(productCategoryList!=null && productCategoryList.size()>0){
        try {
            ProductCategoryExecution pe = productCategoryService.batchAddProductCategory(productCategoryList);
            if(pe.getState()==ProductCategoryStateEnum.SUCCESS.getState()){
                modelMap.put("success",true);
            }else{
                modelMap.put("success",false);
                modelMap.put("errMsg",pe.getStateInfo());
            }
        } catch (ProductCategoryOperationException e) {
            modelMap.put("success",false);
            modelMap.put("srrMsg",e.toString());
            return modelMap;
        }
    }else {
        modelMap.put("success",false);
        modelMap.put("errMsg","请至少输入一个商品类别");
    }
    return modelMap;
}

5. View层的实现

productcategorymanage.js:

$(function () {
    var getProductCategoryURL = '/o2o/shopadmin/getproductcategorylist';
    var addProductCategoryURL = '/o2o/shopadmin/addproductcategory';
    // 加载数据
    getProductCategoryList();

    function getProductCategoryList() {
        $.getJSON(getProductCategoryURL,
            function(data) {
                if (data.success) {
                    var dataList = data.data;
                    $('.product-categroy-wrap').html('');
                    var tempHtml = '';
                    dataList
                        .map(function(item, index) {
                            tempHtml += ''
                                + '<div class="row row-product-category now">'
                                + '<div class="col-33 product-category-name">'
                                + item.productCategoryName
                                + '</div>'
                                + '<div class="col-33">'
                                + item.priority
                                + '</div>'
                                + '<div class="col-33"><a href="#" class="button delete" data-id="'
                                + item.productCategoryId
                                + '">删除</a></div>'
                                + '</div>';
                        });
                    $('.product-categroy-wrap').append(tempHtml);
                }
            });
    }

    //  新增按钮的点击事件
    $('#new').click(
        function(){
            // 新增数据 以 temp 为标识,便于和库表中的数据区分开来
            var tempHtml = '<div class="row row-product-category temp">'
                + '<div class="col-33"><input class="category-input category" type="text" placeholder="分类名"></div>'
                + '<div class="col-33"><input class="category-input priority" type="number" placeholder="优先级"></div>'
                + '<div class="col-33"><a href="#" class="button delete">删除</a></div>'
                + '</div>';
            $('.product-categroy-wrap').append(tempHtml);
        });


    $('#submit').click(function() {
        // 通过temp 获取新增的行
        var tempArr = $('.temp');
        // 定义数组接收新增的数据
        var productCategoryList = [];
        tempArr.map(function(index, item) {
            var tempObj = {};
            tempObj.productCategoryName = $(item).find('.category').val();
            tempObj.priority = $(item).find('.priority').val();
            if (tempObj.productCategoryName && tempObj.priority) {
                productCategoryList.push(tempObj);
            }
        });
        $.ajax({
            url : addProductCategoryURL,
            type : 'POST',
            // 后端通过 @HttpRequestBody直接接收
            data : JSON.stringify(productCategoryList),
            contentType : 'application/json',
            success : function(data) {
                if (data.success) {
                    $ .toast('提交成功!'); 
                    //重新加载数据
                    getProductCategoryList(); 
                } else { 
                    $ .toast('提交失败'); 
                } 
            } 
        }); 
    }); 
}); ```

![在这里插入图片描述](https://img-blog.csdnimg.cn/20200215225238727.gif)

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【校园商铺SSM-18】商品类别批量添加--Dao+Service+Controller+View层的实现

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区