shop--9.商品--商品编辑--修改(后端)

1.首先获取店铺下的商品信息

dao层

/**
     * 由商品Id获取商品信息
     * @param productId
     * @return
     */
    Product queryProductByproductId(Long productId);

  

dao.xml

要重新定义resultMap

因为返回的商品详情图片是一个List,所以要用collection来进行定义,而且在进行数据查询时,要使用多表连接的功能

<resultMap id="productMap" type="com.shop.bean.Product">
        <id column="product_id" property="productId"/>
        <result column="product_name" property="productName"/>
        <result column="product_desc" property="productDesc"/>
        <result column="img_addr" property="imgAddr"/>
        <result column="normal_price" property="normalPrice"/>
        <result column="promotion_price" property="promotionPrice"/>
        <result column="priority" property="priority"/>
        <result column="create_time" property="createTime"/>
        <result column="last_edit_time" property="lastEditTime"/>
        <result column="status" property="status"/>
        <association column="product_category_id" property="productCategory"
                     javaType="com.shop.bean.ProductCategory">
            <id column="product_category_id" property="productCategoryId"/>
            <result column="product_category_name" property="productCategoryName"/>
        </association>
        <association column="shop_id" property="shop" javaType="com.shop.bean.Shop">
            <id column="shop_id" property="shopId"/>
            <result column="shop_name" property="shopName"/>
            <result column="owner_id" property="ownerId"/>
        </association>
        <collection column="product_id" property="productImgList" ofType="com.shop.bean.ProductImg">
            <id column="product_img_id" property="productImgId"/>
            <result column="img_addr" property="imgAddr"/>
            <result column="img_desc" property="imgDesc"/>
            <result column="priority" property="priority"/>
            <result column="create_time" property="createTime"/>
            <result column="product_id" property="productId"/>
        </collection>
    </resultMap>

  

<select id="queryProductByproductId" resultMap="productMap">
        SELECT
        p.product_id,
        p.product_name,
        p.product_desc,
        p.img_addr,
        p.normal_price,
        p.promotion_price,
        p.priority,
        p.create_time,
        p.last_edit_time,
        p.status,
        p.product_category_id,
        p.shop_id,
        pm.product_img_id,
        pm.img_addr,
        pm.img_desc,
        pm.priority,
        pm.create_time,
        pm.product_id
        FROM
        product p
        LEFT JOIN
        product_img pm
        ON
        p.product_id=pm.product_id
        WHERE p.product_id=#{productId}
        ORDER BY
        pm.priority DESC
    </select>

  

service

 /**
     * 由商品Id获取商品信息
     * @param productId
     * @return
     */
    Product getProductByProductId(Long productId);

  

    /**
     * 由商品Id获取商品信息
     * @param productId
     * @return
     */
    @Override
    public Product getProductByProductId(Long productId) {
        return productDao.queryProductByproductId( productId );
    }

  

controller层

@RequestMapping(value="getproductbyid", method=RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getProductById(@RequestParam Long productId){
        Map<String, Object> modelMap = new HashMap<>();
        //Long productId = HttpServletRequestUtil.getLong( request, "productId" );
        if(productId > 0){
            //获取商品Id的商品信息
            Product product = productService.getProductByProductId( productId );
            //获取该店铺下的商品类别列表
            List<ProductCategory> productCategoryList =
                    productCategoryService.getProductCategoryList( product.getShop().getShopId() );
            modelMap.put("success", true);
            modelMap.put( "product", product );
            modelMap.put( "productCategoryList", productCategoryList );
        } else{
            modelMap.put( "success", false );
            modelMap.put( "errMsg", "empty productId" );
        }
        return modelMap;
    }

  

2.新传入的图片(缩略图或详情图)都会覆盖(删除)掉原来的图片

dao层

/**
     * 根据productId获取商品详情图片列表
     * @param productId
     * @return
     */
    List<ProductImg> queryProductImgByProductId(Long productId);

    /**
     * 根据传入的productImgId删除所有商品详情图片
     * @param productId
     * @return
     */
    int deleteProductImgByProductId(Long productId);

  

<!--List<ProductImg> queryProductImgByProductId(Long productId);-->
    <select id="queryProductImgByProductId" resultType="com.shop.bean.ProductImg">
        SELECT
        product_img_id,
        img_addr
        FROM
        product_img
        WHERE
        product_id=#{productId}
    </select>

    <!--int deleteProductImgByProductId(Long productId);-->
    <delete id="deleteProductImgByProductId" parameterType="java.lang.Long">
        DELETE FROM product_img WHERE product_id=#{productId}
    </delete>

3.点击提交按钮之后,提交到后台,修改数据库中的信息

dao层

/**
     * 更新商品信息
     * @param product
     * @return
     */
    int updateProduct(Product product);

  

<update id="updateProduct" parameterType="com.shop.bean.Product">
        UPDATE product
        <set>
            <if test="productName != null">product_name=#{productName},</if>
            <if test="productDesc != null">product_desc=#{productDesc},</if>
            <if test="imgAddr != null">img_addr=#{imgAddr},</if>
            <if test="normalPrice != null">normal_price=#{normalPrice},</if>
            <if test="promotionPrice != null">promotion_price=#{promotionPrice},</if>
            <if test="lastEditTime != null">last_edit_time=#{lastEditTime},</if>
            <if test="status != null">status=#{status},</if>
            <if test="productCategory != null
            and productCategory.productCategoryId != null">product_category_id=#{productCategory.productCategoryId}</if>
        </set>
        WHERE product_id=#{productId}
        AND shop_id=#{shop.shopId}
    </update>

  

service

/**
     * 修改商品信息
     *1.若缩略图参数有值,则处理缩略图
     * 若原来存在缩略图,则先删除文件夹下的缩略图,然后再获取新的缩略图相对路径,并赋值给product
     * 2.若商品详情列表有值,则再处理商品详情图,删除文件夹下的商品详情图
     * 3.将product_img数据库中的商品记录删除
     * 4.更新数据库product_img和product的信息
     * @param product
     * @return
     */
    @Override
    @Transactional
    public ProductExecution modifyProduct(Product product, CommonsMultipartFile thumbnail, List<CommonsMultipartFile> productImgList)
            throws ProductOperationException {
        if(product != null && product.getShop() != null && product.getShop().getShopId() != null){
            try{
                //如果商品缩略图改变了的话,就将原来的商品缩略图删除,再放入新的
                if(thumbnail != null){
                    //从数据库获取传入的商品信息
                    Product tempProduct = productDao.queryProductByproductId( product.getProductId() );
                    //首先判断是否存在根据商品Id有当前要插入的商品信息
                    if(tempProduct != null && tempProduct.getImgAddr() != null){
                        ImageUtil.deleteFileOrPath( tempProduct.getImgAddr() );
                    }
                    addThumbnail( product, thumbnail );
                }

                //如果添加了商品详情图的话,就把原来的商品详情图删掉,再加入新的
                if(productImgList != null && productImgList.size() > 0){
                    deleteProductImgList(product.getProductId());
                    addProductImgList( product, productImgList );
                }
                //添加商品信息中必要的部分
                product.setLastEditTime( new Date(  ) );
                int effectNum = productDao.updateProduct( product );
                if(effectNum > 0){
                    product = productDao.queryProductByproductId( product.getProductId() );
                    return new ProductExecution(ProductStateEnum.SUCCESS, product);
                } else{
                    return new ProductExecution( ProductStateEnum.INNER_ERROR );
                }
            }catch(ProductOperationException e){
                throw new ProductOperationException( "modify product error : " + e.getMessage() );
            }
        } else{
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

  

/**
     * 将商品缩略图添加到用户相对的文件夹下,并将店铺信息中的商品图片信息更新
     * @param product
     * @param thumbnail
     */
    private void addThumbnail(Product product, CommonsMultipartFile thumbnail){
        //获取缩略图的存储途径,直接存储在店铺的文件夹下
        String relativeImgPath = PathUtil.getShopImgPath(product.getShop().getShopId());
        String realRelativeImgPath = ImageUtil.generateThumbnail(thumbnail, relativeImgPath);
        product.setImgAddr( realRelativeImgPath );
    }


/**
     * 批量添加商品详情图片到用户相对的文件夹下,并将其批量插入到数据库中
     * @param product
     * @param productImgList
     */
    private void addProductImgList(Product product, List<CommonsMultipartFile> productImgList){
        //获取图片的存储途径,直接存储在店铺的文件夹下
        String relativeImgPath = PathUtil.getShopImgPath( product.getShop().getShopId() );
        List<ProductImg> productImgs = new ArrayList<>();

        //遍历图片列表进行处理,并且将结果添加到productImgs中
        for(CommonsMultipartFile proImg : productImgList){
            String imgAddr = ImageUtil.generateNormalImg(proImg, relativeImgPath);
            ProductImg productImg = new ProductImg();
            productImg.setImgAddr( imgAddr );
            productImg.setProductId(product.getProductId());
            productImg.setCreateTime( new Date(  ) );
            productImgs.add( productImg );
        }
        if(productImgs.size() > 0){
            try{
                int effectNum = productImgDao.batchInsertProductImg( productImgs );
                if(effectNum <= 0){
                    throw new ProductOperationException("创建商品详情图片失败");
                }
            } catch(Exception e){
                throw new ProductOperationException("创建商品详情图片失败" + e.toString());
            }
        }
    }

  

private void deleteProductImgList(Long productId){
        //从prodcut_img数据库中获取product_id为productId的
        List<ProductImg> productImgList = productImgDao.queryProductImgByProductId(productId);
        if(productImgList != null && productImgList.size() > 0){
            for(ProductImg tempProductImg : productImgList){
                ImageUtil.deleteFileOrPath( tempProductImg.getImgAddr() );
            }
            //删除数据库中原有的照片
            productImgDao.deleteProductImgByProductId( productId );
        }
    }

  

controller层

@RequestMapping(value="/modifyproduct", method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> modifyProduct(HttpServletRequest request){
        Map<String, Object> modelMap = new HashMap<>();
        //校验验证码
        //验证码校验
        if(!CodeUtil.checkVerifyCode(request)){
            modelMap.put( "success", false );
            modelMap.put( "errMsg", "验证码错误" );
            return modelMap;
        }

        //接收前端传来的参数:商品信息,缩略图,商品详情图片
        ObjectMapper objectMapper = new ObjectMapper(  );
        Product product = null;
        String productStr = HttpServletRequestUtil.getString( request, "productStr" );

        CommonsMultipartFile thumbnail = null;
        List<CommonsMultipartFile> productImgList = new ArrayList<>();
        //在本次会话的上下文session中获取上传的文件
        CommonsMultipartResolver commonsMultipartResolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());

        //如果有缩略图,商品详情图的话,就赋值给相应的变量,没有的话,就不管
        if(commonsMultipartResolver.isMultipart( request )){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            thumbnail = (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail");
            for(int i = 0; i < MAXIMAGECOUNT; i++){
                CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile( "productImg" + i);
                if(commonsMultipartFile != null){
                    productImgList.add( commonsMultipartFile );
                } else{
                    break;
                }
            }
        }

        //从ProductStr字符串中,利用ObjectMapper将productStr转化为其Product实体类
        try{
            product = objectMapper.readValue(productStr, Product.class);
        } catch (Exception e) {
            modelMap.put( "success", false );
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }

        //如果product不是null,则进行商品修改
        if(product != null){
            try{
                Shop shop = new Shop();
                shop.setShopId( 1L );
                product.setShop(shop);

                ProductExecution productExecution = productService.modifyProduct( product, thumbnail, productImgList );
                if(productExecution.getState() == ProductStateEnum.SUCCESS.getState()){
                    modelMap.put("success", true);
                } else{
                    modelMap.put( "success", false );
                    modelMap.put( "errMsg", productExecution.getStateInfo() );
                }
            }catch(RuntimeException e){
                modelMap.put( "success", false );
                modelMap.put( "errMsg", e.toString() );
                return modelMap;
            }
        } else{
            modelMap.put( "success", false );
            modelMap.put( "errMsg", "请输入商品信息");
        }
        return modelMap;
    }

  

 

posted @ 2018-05-06 22:32  SkyeAngel  阅读(430)  评论(0编辑  收藏  举报