Mybatis-PageHelper分页/动态排序/对List遍历/where语句动态拼装

1. Mybatis-PageHelper高效准确地分页及动态排序

Mybatis-PageHelper下载地址:
https://github.com/pagehelper/Mybatis-PageHelper

步骤如下:

  1. 传入参数:PageHelper.startPage(pageNum,pageSize);
  2. 对结果进行封装: PageInfo pageInfo = new PageInfo(productList);
  3. 返回结果
  4. 其中orderBy参数为排序字段,如果想按照倒序或者顺序则将orserBy参数进行拼接
String orderBy = 排序字段 + " desc";//按照排序字段 倒序 排序
        //传入参数
        PageHelper.startPage(pageNum,pageSize);
        //排序处理
        if(StringUtils.isNotBlank(orderBy)){
            if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                //Mybatis-PageHelper实现动态排序  Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc");
                PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
            }
        }
        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);

2. Mybatis对List遍历的实现方法

当参数为List集合的时候

List<Product> selectByNameAndCategoryIds(@Param("productName")String productName,@Param("categoryIdList")List<Integer> categoryIdList);

使用进行遍历。

  <select id="selectByNameAndCategoryIds" resultMap="BaseResultMap" parameterType="map">
    SELECT
    <include refid="Base_Column_List"></include>
    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>

3. Mybatis对where语句动态拼装

List<Product> selectByNameAndProductId(@Param("productName")String productName,@Param("productId") Integer productId);

当传入的参数productName和productId都有可能为null的时候,需要进行判断,当productName为null 的时候,会自动忽略productId前的AND。

  <select id="selectByNameAndProductId" resultMap="BaseResultMap" parameterType="map">
    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>

猜你喜欢

转载自blog.csdn.net/ouzhuangzhuang/article/details/87877906