Mybatis/Mybatis Plus - PageHelper 的基础示例
导入依赖
file:[pom.xml]
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
使用案例
public PageInfo<PostModel> findAllByCriteriaNotComments(DiscussionCriteria criteria) {
// 如果 page size 为空,返回 5 默认值
int pageSize = Optional.ofNullable(criteria.getPageSize()).orElse(5);
int currPage = Optional.ofNullable(criteria.getCurrPage()).orElse(1);
return PageHelper.startPage(currPage, pageSize).doSelectPageInfo(() -> discussionMapper.findAllByCriteriaNotComments(criteria));
}
最好使用 ISelect
接口调用,因为这种方式是极其安全的。具体原因查看官方文档的说明:如何使用分页查询。简单来说,就是在调用 startPage
静态方法之后没有紧接着 mybatis 查询,会产生一个分页参数,没有被消费就不会被清除,一直存留着。要么手动 try,然后在 finally 块手动清除 PageHelper.clearPage()
。
注意事项
在调用联表查询时(即 join),通过 PageHelper 分页查询会导致查询的数量不正确。具体原因可以查看这个博客说的:使用pagehelper进行连表查询时查询条数和分页数不符。
应当改造其为子查询的方式,如下列所示。
子查询
<resultMap id="findAllByCriteriaNotCommentsMap" type="com.bleuon.entity.PostModel" autoMapping="true">
<id column="id" property="id"/>
<association javaType="com.bleuon.entity.dto.ConsumerDTO" property="consumer" column="{consumerId=consumer_id}"
select="findConsumerById">
</association>
</resultMap>
<select id="findAllByCriteriaNotComments" resultMap="findAllByCriteriaNotCommentsMap">
SELECT *
FROM t_posts
<where>
<trim prefix="AND" prefixOverrides="AND">
<if test="postId != null and postId != ''">
AND id = #{postId}
</if>
<if test="consumerId != null and consumerId != ''">
AND consumer_id = #{consumerId}
</if>
<if test="title != null and title != ''">
AND title LIKE CONCAT('%', #{title}, '%')
</if>
<if test="rankingType != null and rankingType != ''">
AND ranking_type = #{rankingType}
</if>
<if test="type != null and type != ''">
AND type = #{type}
</if>
</trim>
</where>
<if test="sequences != null">
ORDER BY
<foreach collection="sequences" item="sequence" separator=", ">
<choose>
<when test="sequence.isAsc == true">
${sequence.col} ASC
</when>
<otherwise>
${sequence.col} DESC
</otherwise>
</choose>
</foreach>
</if>
</select>
写 SQL 语句时一定要注意不能给语句末尾处添加 ;
,否则 PageHelper 拼接的 sql 是错误的。
分类:
软件开发 / Web 后端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步