一、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>
分类:
【SSM电商后台项目】
本文详细介绍MyBatis-PageHelper插件实现分页及动态排序的方法,包括参数设置、SQL动态组装技巧,并覆盖MyBatis中List遍历及where语句动态拼装等实用技能。

470

被折叠的 条评论
为什么被折叠?



