当 url 不传categoryId
时categoryIdList
为空数组
ProductServiceImp 中 List<Product> productList = productMapper.selectByNameAndCategoryIds(keyword, categoryIdList);
此处直接传人 keyword 和 categoryIdList
因为 sql 代码只检查了categoryIdList == null
并未对 categoryIdList
是空数组进行校验
public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy) {
if (StringUtils.isBlank(keyword) && categoryId == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
}
List<Integer> categoryIdList = new ArrayList<Integer>();
if (categoryId != null) {
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if (category == null && StringUtils.isBlank(keyword)) {
//没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
PageHelper.startPage(pageNum, pageSize);
List<ProductListVo> productListVoList = Lists.newArrayList();
PageInfo pageInfo = new PageInfo(productListVoList);
return ServerResponse.createBySuccess(pageInfo);
}
categoryIdList = iCategoryService.selectCategoryAndChildrenById(categoryId).getData();
}
if (StringUtils.isNotBlank(keyword)) {
// 为了配合数据库的模糊查询,所以把关键词进行重新拼接
keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
}
// 排序同样用PageHelper实现
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]);
}
}
// 错误写法
// List<Product> productList = productMapper.selectByNameAndCategoryIds(keyword, categoryIdList);
List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);
List<ProductListVo> 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);
}
sql代码
<select id="selectByNameAndCategoryIds" resultMap="BaseResultMap" parameterType="map">
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 item="item" index="index" open="(" separator="," close=")" collection="categoryIdList">
#{item}
</foreach>
</if>
</select>
网友评论