美文网首页
7.商品管理

7.商品管理

作者: 惜小八 | 来源:发表于2020-05-28 16:29 被阅读0次

    商品管理模块后台主要功能(7个)有:商品更新/商品添加、商品搜索、商品列表、商品上下架、商品详情、富文本上传图片、SpringMVC上传图片。其中商品的更新和添加写在同一个方法当中,通过是否有id进行判断处理,当中是更新时id已存在,当为添加时id还不存在,添加后才有ID。
    商品上下架:系统前台传递productId和status和系统后台,系统后台根据productId对产品进行上下架处理。

    商品管理模块前台的主要功能(4个)有:商品详细detail、商品列表list,
    产品详情: 根据传递的productID,查询产品的详情
    产品列表:根据keyword、categoryId、orderBy对商品进行搜索,逻辑是:首先判断keyword、categoryId参数的有效性,为null则返回参数异常。然后判断categoryId对应的category是否存在,此时要注意,就算查处来为null,也不能返回错误,使用PageInfo返回空即可。然后组装keyword为模糊查询,以及获得categoryId/父子/祖父为categoryId的category,组装为Product,然后进行查询分页。

    ******************************controller******************************
    
    package com.mall.controller.backend;
    
    import com.github.pagehelper.PageInfo;
    import com.google.common.collect.Maps;
    import com.mall.common.Const;
    import com.mall.common.ResponseCode;
    import com.mall.common.ServerResponse;
    import com.mall.pojo.Product;
    import com.mall.pojo.User;
    import com.mall.service.IFileService;
    import com.mall.service.IProductService;
    import com.mall.service.IUserService;
    import com.mall.util.PropertiesUtil;
    import com.mall.vo.ProductDetailVo;
    import java.util.List;
    import java.util.Map;
    
    import com.mall.vo.ProductListVo;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpRequest;
    import org.springframework.stereotype.Controller;
    import org.springframework.stereotype.Service;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    @Controller
    @RequestMapping(value = "/product/manage/")
    public class ProductManageController {
    
        @Autowired
        private IUserService iUserService;
        @Autowired
        private IProductService iProductService;
        @Autowired
        private IFileService iFileService;
    
        //插入或者更新产品
        @ResponseBody
        @RequestMapping("product_save.do")
        public ServerResponse productSave(HttpSession session, Product product){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //更新或者插入产品
                return iProductService.saveOrUpdateProduct(product);
            }
            return response;
        }
    
        @ResponseBody
        @RequestMapping("set_sale_status.do")
        public ServerResponse setSaleStatus(HttpSession session,Integer productId, Integer status){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //设置产品的销售状态
                return iProductService.setSaleStatus(productId, status);
            }
            return response;
        }
    
        @ResponseBody
        @RequestMapping("get_product_detail.do")
        public ServerResponse<ProductDetailVo> getProductDetail(HttpSession session, Integer productId){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //设置产品的销售状态
                return iProductService.getManagerProductDetail(productId);
            }
            return response;
        }
    
        @ResponseBody
        @RequestMapping("list.do")
        public ServerResponse<PageInfo> list(HttpSession session, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize" ,defaultValue = "10") int pageSize){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //设置产品的销售状态
                return iProductService.getProductList(pageNum, pageSize);
            }
            return response;
        }
    
        @ResponseBody
        @RequestMapping("search.do")
        public ServerResponse<PageInfo> searchProduct(HttpSession session,String productName,Integer productId, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize" ,defaultValue = "10") int pageSize){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //设置产品的销售状态
                return iProductService.searchProduct(productName, productId, pageNum, pageSize);
            }
            return response;
        }
    
        //从request的session里面拿到Servlet的上下文,此时upload和WEB-INF是同级目录
        @ResponseBody
        @RequestMapping("upload.do")
        public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile multipartFile, HttpServletRequest request){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            if(user == null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getMsg());
            }
            ServerResponse response=iUserService.checkUserRole(user);
            if(response.isSuccess()){
                //前端需要的是url,uri,此处使用map集合进行返回
                //获取Servlet的上下文,表示要上传的地方是哪里
                String path=session.getServletContext().getRealPath("/WEB-INF/upload");
                String targetFileName=iFileService.upload(multipartFile,path);
                String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+"/"+targetFileName;
    
                Map fileMap= Maps.newHashMap();
                fileMap.put("url",url);
                fileMap.put("uri",targetFileName);
                return ServerResponse.createBySuccess(fileMap);
            }
            return response;
        }
    
    
        @ResponseBody
        @RequestMapping("rich_img_upload.do")
        public Map richTextUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response){
            User user=(User)session.getAttribute(Const.CURRENT_USER);
            Map resultMap=Maps.newHashMap();
            if(user == null){
                resultMap.put("success",false);
                resultMap.put("msg","用户未登陆");
                return resultMap;
            }
    
            if(iUserService.checkUserRole(user).isSuccess()){
                //首先判断文件是否为空
                if(multipartFile.isEmpty()){
                    resultMap.put("success",false);
                    resultMap.put("msg","上传文件为空");
                    return resultMap;
                }
                /**
                 * 此处使用的富文本是simditor,所以返回的类型要符合simditor
                 * "success":true/false
                 *    "msg":"error message"
                 * "file_path":"real file path"
                 *
                 * 除此之外,simditor对HttpServletResponse也有要求
                 */
                String path=session.getServletContext().getRealPath("/WEB-INF/upload");
                String targetFileName=iFileService.upload(multipartFile,path);
                if(StringUtils.isBlank(targetFileName)){
                    resultMap.put("success",false);
                    resultMap.put("msg","上传文件失败");
                    return resultMap;
                }
                String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+"/"+targetFileName;
    
                resultMap.put("success",true);
                resultMap.put("msg","上传文件成功");
                resultMap.put("file_path",url);
                response.addHeader("Access-Control-Allow-Headers","X-File-Name");
                return resultMap;
            }
            resultMap.put("success",false);
            resultMap.put("msg","用户无权限操作");
            return resultMap;
        }
    
    }
    ************************************************************
    package com.mall.controller.portal;
    
    import com.github.pagehelper.PageInfo;
    import com.mall.common.ServerResponse;
    import com.mall.service.IProductService;
    import com.mall.vo.ProductDetailVo;
    import com.mall.vo.ProductListVo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/product/")
    public class ProductController {
    
        @Autowired
        private IProductService iProductService;
    
        @ResponseBody
        @RequestMapping("detail.do")
        public ServerResponse<ProductDetailVo> detail(Integer productId){
            return iProductService.getProductDetail(productId);
        }
        @ResponseBody
        @RequestMapping("list.do")
        public ServerResponse<PageInfo> list(@RequestParam(value = "keyWord",required = false) String keyWord,@RequestParam(value = "categoryId",required = false) Integer categoryId,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize" ,defaultValue = "10") int pageSize,@RequestParam(value = "orderBy" ,defaultValue = "")String oderBy){
            return iProductService.getProductByKeywordCategoryId(keyWord, categoryId, pageNum, pageSize, oderBy);
        }
    
    }
    
    ****************************service********************************
    package com.mall.service.impl;
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.google.common.collect.Lists;
    import com.mall.common.Const;
    import com.mall.common.ResponseCode;
    import com.mall.common.ServerResponse;
    import com.mall.dao.CategoryMapper;
    import com.mall.dao.ProductMapper;
    import com.mall.pojo.Category;
    import com.mall.pojo.Product;
    import com.mall.service.ICategoryService;
    import com.mall.service.IProductService;
    import com.mall.util.DateTimeUtils;
    import com.mall.util.PropertiesUtil;
    import com.mall.vo.ProductDetailVo;
    import com.mall.vo.ProductListVo;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service("iProductService")
    public class ProductServiceImpl implements IProductService {
    
        @Autowired
        private ProductMapper productMapper;
        @Autowired
        private CategoryMapper categoryMapper;
        @Autowired
        private ICategoryService categoryService;
    
        public ServerResponse<String> saveOrUpdateProduct(Product product){
            if(product !=null){
                if(StringUtils.isNotBlank(product.getSubImages())){
                    String [] subImagesArray=product.getSubImages().split(",");
                    if(subImagesArray.length>0){
                        product.setMainImage(subImagesArray[0]);
                    }
                    //在新增之前是没有id的,新增之后自动生成id
                    if(product.getId() != null){
                        productMapper.updateByPrimaryKey(product);
                        return ServerResponse.createBySuccess("更新产品成功");
                    }else {
                        int rowCount=productMapper.insert(product);
                        if(rowCount>0){
                            return ServerResponse.createBySuccess("插入产品成功");
                        }
                        return ServerResponse.createBySuccess("插入产品失败");
                    }
                }
                return ServerResponse.createByErrorMsg("子图不能为空");
            }
            return ServerResponse.createByErrorMsg("参数错误");
        }
    
        public ServerResponse<String> setSaleStatus(Integer productId,Integer status){
            if(productId==null || status==null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
            Product product=new Product();
            product.setId(productId);
            product.setStatus(status);
            int rowCount=productMapper.updateByPrimaryKeySelective(product);
            if(rowCount>0){
                return ServerResponse.createBySuccess("更新产品状态成功");
            }
            return ServerResponse.createBySuccess("更新产品状态失败");
        }
    
        public ServerResponse<ProductDetailVo> getManagerProductDetail(Integer productId){
            if(productId==null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
            Product product=productMapper.selectByPrimaryKey(productId);
            if(product==null){
                return ServerResponse.createByErrorMsg("产品已删除");
            }
            ProductDetailVo productDetailVo=assembleProductDetailVo(product);
            return ServerResponse.createBySuccess(productDetailVo);
        }
        private ProductDetailVo assembleProductDetailVo(Product product){
    
            ProductDetailVo productDetailVo=new ProductDetailVo();
            productDetailVo.setId(product.getId());
            productDetailVo.setSubtitle(product.getSubtitle());
            productDetailVo.setPrice(product.getPrice());
            productDetailVo.setMainImage(product.getMainImage());
            productDetailVo.setSubImages(product.getSubImages());
            productDetailVo.setCategoryId(product.getCategoryId());
            productDetailVo.setDetail(product.getDetail());
            productDetailVo.setName(product.getName());
            productDetailVo.setStatus(product.getStatus());
            productDetailVo.setStock(product.getStock());
    
            //imageHost
            productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
            //parentCategoryId
            Category category=categoryMapper.selectByPrimaryKey(product.getCategoryId());
            if(category==null){
                productDetailVo.setParentCategoryId(0);//默认为根节点
            }else{
                productDetailVo.setParentCategoryId(category.getParentId());
              }
          
            //createTime
            productDetailVo.setCreateTime(DateTimeUtils.dateToStr(product.getCreateTime()));
            //updateTime
            productDetailVo.setUpdateTime(DateTimeUtils.dateToStr(product.getUpdateTime()));
    
            return productDetailVo;
        }
    
        public ServerResponse<PageInfo> getProductList(int pageNum, int pageSize){
            PageHelper.startPage(pageNum, pageSize);
            List<Product> productList=productMapper.selectProductList();
            List<ProductListVo> productListVoList= Lists.newArrayList();
            for (Product product:productList){
                productListVoList.add(assembleProductListVo(product));
            }
            PageInfo pageInfo=new PageInfo(productList);
            pageInfo.setList(productListVoList);
            return ServerResponse.createBySuccess(pageInfo);
        }
        private ProductListVo assembleProductListVo(Product product){
            ProductListVo productListVo=new ProductListVo();
            productListVo.setId(product.getId());
            productListVo.setCategoryId(product.getCategoryId());
            productListVo.setMainImage(product.getMainImage());
            productListVo.setPrice(product.getPrice());
            productListVo.setName(product.getName());
            productListVo.setStatus(product.getStatus());
            productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
            return productListVo;
        }
    
        public ServerResponse<PageInfo> searchProduct(String productName,Integer productId,int pageNum,int pageSize){
    
            PageHelper.startPage(pageNum, pageSize);
            if(StringUtils.isNotBlank(productName)){
                productName=new StringBuilder().append("%").append(productName).append("%").toString();
            }
            List<Product> productList=productMapper.selectProductByProductNameAndProductId(productName,productId);
            List<ProductListVo> productListVoList=Lists.newArrayList();
            for (Product product:productList){
                productListVoList.add(assembleProductListVo(product));
            }
            PageInfo pageInfo=new PageInfo(productList);
            pageInfo.setList(productListVoList);
            return ServerResponse.createBySuccess(pageInfo);
        }
    
    
    
    
    
        //portal
        public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
            if(productId==null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
            Product product=productMapper.selectByPrimaryKey(productId);
            if(product==null || product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()){
                return ServerResponse.createByErrorMsg("产品已下架");
            }
            ProductDetailVo productDetailVo=assembleProductDetailVo(product);
            return ServerResponse.createBySuccess(productDetailVo);
        }
    
        public ServerResponse<PageInfo> getProductByKeywordCategoryId(String keyword,Integer categoryId,int pageNum, int pageSize,String orderBy){
            if(StringUtils.isBlank(keyword)  && categoryId==null){
                return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
            List<Integer> categoryIdList=Lists.newArrayList();
            if(categoryId !=null){
                Category category=categoryMapper.selectByPrimaryKey(categoryId);
                //没有该分类,也没有关键字,不会报错
                if(category==null && StringUtils.isBlank(keyword)){
                    PageHelper.startPage(pageNum, pageSize);
                    List<ProductListVo> productListVoList= Lists.newArrayList();
                    PageInfo pageResult=new PageInfo(productListVoList);
                    return ServerResponse.createBySuccess(pageResult);
                }
    
                //categoryId组装
                categoryIdList= categoryService.getCategoryAndDeepChildrenCategory(category.getId()).getData();
            }
    
            //keyword组装
            if(StringUtils.isNotBlank(keyword)){
                keyword=new StringBuilder().append("%").append(keyword).append("%").toString();
            }
    
            PageHelper.startPage(pageNum, pageSize);
            //排序处理
            if(StringUtils.isNotBlank(orderBy)){
                if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                    String [] orderByArray=orderBy.split("_");
                    PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
                }
            }
    
            //使用keyword和categoryID进行查询
            List<Product> productList=productMapper.selectProductByKeywordCategoryIdList(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);
    
            List<ProductListVo> productListVoList=Lists.newArrayList();
            for(Product product:productList){
                productListVoList.add(this.assembleProductListVo(product));
            }
            PageInfo pageInfo=new PageInfo(productList);
            pageInfo.setList(productListVoList);
            return ServerResponse.createBySuccess(pageInfo);
        }
    
    
    
    
    }
    
    
    ****************************图片上传Service********************************
    package com.mall.service.impl;
    
    import com.google.common.collect.Lists;
    import com.mall.service.IFileService;
    import com.mall.util.FTPUtil;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    
    
    @Service("iFileService")
    public class FileServiceImpl implements IFileService {
    
        private Logger logger= LoggerFactory.getLogger(FileServiceImpl.class);
    
        public String upload(MultipartFile multipartFile,String path){
            String fileName=multipartFile.getOriginalFilename();//获取原文件名
            String extendsName=fileName.substring(fileName.lastIndexOf("."));//.jpg
    
            //上传文件的名字
            String uploadFileName= UUID.randomUUID().toString()+extendsName;
            logger.info("开始上传文件,上传文件的文件名是:{},上传的路径是:{},新文件名:{}",fileName,path,uploadFileName);
            File targetFile=new File(path,uploadFileName);
            if(!targetFile.exists()){
                targetFile.setWritable(true);//给予写权限
                targetFile.mkdirs();
            }
            try {
                multipartFile.transferTo(targetFile);//上传文件成功,已上传到upload下了
    
                //将文件上传到ftp服务器上
                FTPUtil.upload(Lists.newArrayList(targetFile));
                //将upload上的文件删除
                targetFile.delete();
    
            } catch (IOException e) {
                logger.error("上传文件异常",e);
                return null;
            }
            return targetFile.getName();
        }
    
    }
    
    ****************************图片上传工具类********************************
    package com.mall.util;
    
    import org.apache.commons.net.ftp.FTPClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.List;
    
    //文件上传到ftp服务器
    public class FTPUtil {
    
        private static Logger logger= LoggerFactory.getLogger(FTPUtil.class);
        private static String ftpIp=PropertiesUtil.getProperty("ftp.server.ip");
        private static String ftpUser=PropertiesUtil.getProperty("ftp.user");
        private static String ftpPass=PropertiesUtil.getProperty("ftp.pass");
    
        private String ip;
        private Integer port;
        private String username;
        private String password;
        private FTPClient ftpClient;
    
        public FTPUtil(String ip, Integer port, String username, String password) {
            this.ip = ip;
            this.port = port;
            this.username = username;
            this.password = password;
        }
    
        public static boolean upload(List<File> fileList){
            FTPUtil ftpUtil=new FTPUtil(ftpIp,21,ftpUser,ftpPass);
            logger.info("开始连接FTP服务器");
            //上传文件至ftp服务器的img目录下(如果没有img,会自动创建)
            boolean result=ftpUtil.upload("img",fileList);
            logger.info("结束连接ftp服务器,结束上传,上传结果:{}",result);
            return result;
        }
    
        public boolean upload(String remotePath, List<File> fileList) {
            boolean upload = true;
            FileInputStream fileInputStream=null;
            if(this.connectServer(ip,username,password)){
                try {
                    //可不可切换文件夹,在本文当中传的是img,所以可以切换到img下,如果传的是空,则不能切换
                    ftpClient.changeWorkingDirectory(remotePath);
                    ftpClient.setControlEncoding("UTF-8");
                    //文件以二进制上传,避免乱码
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftpClient.setBufferSize(1024);
                    for(File fileItem:fileList){
                        fileInputStream=new FileInputStream(fileItem);
                        /**
                         * ftpClient.storeFile(String, inputStream)将流写到ftp上,String是保存后的文件名
                         * 注意storeFile(存储文件)里面是file.getName,不是remoteFile
                         * 存储fileItem.getName()文件,以fileInputStream流的形式
                         */
                        ftpClient.storeFile(fileItem.getName(),fileInputStream);
                    }
    
                } catch (IOException e) {
                    logger.error("上传文件到FTP服务器异常",e);
                    upload=false;
                }finally {
                    try {
                        fileInputStream.close();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        logger.error("关闭ftp流异常",e);
                        e.printStackTrace();
                    }
                }
            }
            return upload;
        }
    
        //连接并登陆FTP服务器
        private  boolean connectServer(String ip, String username, String password){
            ftpClient=new FTPClient();
            boolean isSuccess=true;
            try {
                ftpClient.connect(ip);//连接ftp服务器
                logger.info("连接FTP服务器成功,用户开始登陆");
                isSuccess=ftpClient.login(username, password);//登陆ftp服务器
            } catch (IOException e) {
                logger.error("连接ftp服务器失败",e);
            }
            return isSuccess;
        }
    
    }
    
    
    ******************************xml*************************
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.mall.dao.ProductMapper" >
      <resultMap id="BaseResultMap" type="com.mall.pojo.Product" >
        <constructor >
          <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="category_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="subtitle" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="main_image" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="sub_images" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="detail" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="price" jdbcType="DECIMAL" javaType="java.math.BigDecimal" />
          <arg column="stock" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="status" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
          <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
        </constructor>
      </resultMap>
      <sql id="Base_Column_List" >
        id, category_id, name, subtitle, main_image, sub_images, detail, price, stock, status, 
        create_time, update_time
      </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from mmall_product
        where id = #{id,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from mmall_product
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="com.mall.pojo.Product" >
        insert into mmall_product (id, category_id, name, 
          subtitle, main_image, sub_images, 
          detail, price, stock, 
          status, create_time, update_time
          )
        values (#{id,jdbcType=INTEGER}, #{categoryId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 
          #{subtitle,jdbcType=VARCHAR}, #{mainImage,jdbcType=VARCHAR}, #{subImages,jdbcType=VARCHAR}, 
          #{detail,jdbcType=VARCHAR}, #{price,jdbcType=DECIMAL}, #{stock,jdbcType=INTEGER}, 
          #{status,jdbcType=INTEGER}, now(), now()
          )
      </insert>
      <insert id="insertSelective" parameterType="com.mall.pojo.Product" >
        insert into mmall_product
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="categoryId != null" >
            category_id,
          </if>
          <if test="name != null" >
            name,
          </if>
          <if test="subtitle != null" >
            subtitle,
          </if>
          <if test="mainImage != null" >
            main_image,
          </if>
          <if test="subImages != null" >
            sub_images,
          </if>
          <if test="detail != null" >
            detail,
          </if>
          <if test="price != null" >
            price,
          </if>
          <if test="stock != null" >
            stock,
          </if>
          <if test="status != null" >
            status,
          </if>
          <if test="createTime != null" >
            create_time,
          </if>
          <if test="updateTime != null" >
            update_time,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="categoryId != null" >
            #{categoryId,jdbcType=INTEGER},
          </if>
          <if test="name != null" >
            #{name,jdbcType=VARCHAR},
          </if>
          <if test="subtitle != null" >
            #{subtitle,jdbcType=VARCHAR},
          </if>
          <if test="mainImage != null" >
            #{mainImage,jdbcType=VARCHAR},
          </if>
          <if test="subImages != null" >
            #{subImages,jdbcType=VARCHAR},
          </if>
          <if test="detail != null" >
            #{detail,jdbcType=VARCHAR},
          </if>
          <if test="price != null" >
            #{price,jdbcType=DECIMAL},
          </if>
          <if test="stock != null" >
            #{stock,jdbcType=INTEGER},
          </if>
          <if test="status != null" >
            #{status,jdbcType=INTEGER},
          </if>
          <if test="createTime != null" >
            now(),
          </if>
          <if test="updateTime != null" >
            now(),
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.mall.pojo.Product" >
        update mmall_product
        <set >
          <if test="categoryId != null" >
            category_id = #{categoryId,jdbcType=INTEGER},
          </if>
          <if test="name != null" >
            name = #{name,jdbcType=VARCHAR},
          </if>
          <if test="subtitle != null" >
            subtitle = #{subtitle,jdbcType=VARCHAR},
          </if>
          <if test="mainImage != null" >
            main_image = #{mainImage,jdbcType=VARCHAR},
          </if>
          <if test="subImages != null" >
            sub_images = #{subImages,jdbcType=VARCHAR},
          </if>
          <if test="detail != null" >
            detail = #{detail,jdbcType=VARCHAR},
          </if>
          <if test="price != null" >
            price = #{price,jdbcType=DECIMAL},
          </if>
          <if test="stock != null" >
            stock = #{stock,jdbcType=INTEGER},
          </if>
          <if test="status != null" >
            status = #{status,jdbcType=INTEGER},
          </if>
          <if test="createTime != null" >
            create_time = #{createTime,jdbcType=TIMESTAMP},
          </if>
          <if test="updateTime != null" >
            update_time = now(),
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.mall.pojo.Product" >
        update mmall_product
        set category_id = #{categoryId,jdbcType=INTEGER},
          name = #{name,jdbcType=VARCHAR},
          subtitle = #{subtitle,jdbcType=VARCHAR},
          main_image = #{mainImage,jdbcType=VARCHAR},
          sub_images = #{subImages,jdbcType=VARCHAR},
          detail = #{detail,jdbcType=VARCHAR},
          price = #{price,jdbcType=DECIMAL},
          stock = #{stock,jdbcType=INTEGER},
          status = #{status,jdbcType=INTEGER},
          create_time = #{createTime,jdbcType=TIMESTAMP},
          update_time = now()
        where id = #{id,jdbcType=INTEGER}
      </update>
    
      <select id="selectProductList" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mmall_product
        order by id asc
      </select>
    
      <select id="selectProductByProductNameAndProductId" parameterType="map" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mmall_product
        <where>
          <if test="productName !=null">
             and name like #{productName}
          </if>
          <if test="productId != null">
             and id= #{productId}
          </if>
        </where>
      </select>
    
      <select id="selectProductByKeywordCategoryIdList" parameterType="map" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mmall_product
        where status=1
        <if test="productName != null">
          and name like #{productName}
        </if>
        <if test="categoryIdList != null">
          and category_id in
          <foreach collection="categoryIdList" item="item" index="index" separator="," open="(" close=")">
            #{item}
          </foreach>
        </if>
      </select>
    </mapper>
    

    相关文章

      网友评论

          本文标题:7.商品管理

          本文链接:https://www.haomeiwen.com/subject/jcdaahtx.html