Mybatis对List遍历的实现方法

ProductMapper.xml

  <select id="selectByNameAndCategoryIds" resultMap="BaseResultMap" parameterType="map">
    select
    "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
      "item"  index="index"  open="(" separator=","  close=")" collection="categoryIdList">
        #{item}
      
    if>
  select>

dao接口

public interface ProductMapper {

    List selectByNameAndCategoryIds(@Param("productName")String productName ,@Param("categoryIdList")List categoryIdList);
}

service层

public ServerResponse getProductByKeywordCategory(String keyword,Integer categoryId,String orderBy,int pageNum,int pageSize){
        if(StringUtils.isBlank(keyword) && categoryId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List categoryIdList = new ArrayList();

        if(categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if(category == null && StringUtils.isBlank(keyword)){
                //没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
                PageHelper.startPage(pageNum,pageSize);
                List productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            categoryIdList = iCategoryService.selectCategoryAndChildrenById(category.getId()).getData();
        }
        //泛型可以简化对象之间的强转
        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]);
            }
        }

 //对name和categoryIds的校验,当参数非法时,将name置为null或categoryIdList置为null。为保证和mybatis里sql语句对应
        List productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);

        List productListVoList = Lists.newArrayList();
        for(Product product : productList){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVoList.add(productListVo);
        }

        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

你可能感兴趣的:(项目经验,mybatis)