一、Mybatis-PageHelper實現分頁
public ServerResponse<PageInfo> manageGetProductList(int pageNum, int pageSize){ //startPage--start //填充自己的sql查詢邏輯 //pageHelper-收尾 PageHelper.startPage(pageNum, pageSize); List<Product> productList = productMapper.selectProductList(); List<ProductListVo> productListVoList = Lists.newArrayList(); for (Product product : productList){ ProductListVo productListVo = assembleProductListVo(product); productListVoList.add(productListVo); } //給前端的是productListVO,但是需要productList進行分頁 PageInfo pageInfo = new PageInfo(productList); pageInfo.setList(productListVoList); return ServerResponse.createBySuccess(pageInfo); }
主要代碼:
//startPage--start //填充自己的sql查詢邏輯 //pageHelper-收尾 //傳入參數 PageHelper.startPage(pageNum, pageSize); //對結果進行封裝 PageInfo pageInfo = new PageInfo(productList); //返回 return pageInfo ;
二、Mybatis-PageHelper實現動態排序
//排序處理 PageHelper的排序參數格式:price asc; price desc; if (StringUtils.isNotBlank(orderBy)){ if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){ String[] orderByArray = orderBy.split("_"); PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]); } }
傳入的參數orderBy形式:price_asc或price_desc,傳入到PageHelper中為price asc。
可以進行封裝成枚舉類或內部接口
public interface ProductListOrderBy{ //Set查詢效率為O(1), List為O(n) Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc"); }
三、Mybatis中對List遍歷
當Mybatis中參數為List的時候,需要遍歷List中參數。
如:
List<Product> selectByNameAndCategoryIds(@Param("keyword") String productName, @Param("categoryList") List<Integer> categoryList);
底層實現:
使用
<foreach></foreach>進行遍歷。
<select id="selectByNameAndCategoryIds" 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="categoryList != null"> and category_id in <foreach collection="categoryList" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> </if> </select>
四、Mybatis中where語句動態拼裝
方法:
List<Product> selectByNameAndId(@Param("productName") String productName,
@Param("productId") Integer productId);
當傳入的參數productName和productId都有可能為null的時候,需要在底層實現進行判斷。
where <if test="productName != null"> name LIKE #{productName} </if> <if test="productId != null"> AND id = #{productId} </if>
這樣當productName為null的時候,整個語句變為
where and id = #{productId}
而使用<where>標簽可以避免這個問題。
<where>
<if test="productName != null">
AND name LIKE #{productName}
</if>
<if test="productId != null">
AND id = #{productId}
</if>
</where>
當productName為null 的時候,會自動忽略productId前的AND。
完整實現:
<select id="selectByNameAndId" 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>
