loading

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 是错误的。

posted @ 2023-07-01 01:12  Himmelbleu  阅读(8)  评论(0编辑  收藏  举报