ProductMapper.xml
<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>
dao接口
public interface ProductMapper {
List<Product> selectByNameAndCategoryIds(@Param("productName")String productName ,@Param("categoryIdList")List<Integer> categoryIdList);
}
service层
public ServerResponse<PageInfo> 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<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(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<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)
}