实现分页功能

1、Limit实现分页

通过SQL的Limit实现基本的分页功能。SQL层面的分页实现。

【示例】接口

public interface ArticleMapper {

    List<Article> getArticlesByLimit(Map<String,Integer> map);
}

【示例】Mapper.xml

<mapper namespace="com.singerw.mapper.ArticleMapper">
    <select id="getArticlesByLimit" resultType="Article" parameterType="map">
        select * from article limit #{page},#{pageSize};
    </select>
</mapper>

【示例】单元测试

public class ArticleMapperTest {

    @Test
    public void getArticleByLimit() {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("page",0);
        map.put("pageSize",10);
        List<Article> articles = mapper.getArticlesByLimit(map);
        articles.forEach(System.out::println);
    }
}

2、RowBounds实现分页

通过Java代码层面实现分页功能。

【示例】接口

public interface ArticleMapper {

    List<Article> getArticlesByRowBounds();
}

【示例】Mapper.xml

<mapper namespace="com.singerw.mapper.ArticleMapper">
    <select id="getArticlesByRowBounds" resultType="Article">
        select * from article;
    </select>
</mapper>

【示例】单元测试

public class ArticleMapperTest {

    @Test
    public void getArticleByRowBounds() {
        RowBounds rowBounds = new RowBounds(0,10);
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        List<Article> articles = sqlSession.selectList("com.singerw.mapper.ArticleMapper.getArticlesByRowBounds",null,rowBounds);
        articles.forEach(System.out::println);
        sqlSession.close();
    }
}

3、MyBatis 分页插件 PageHelper实现分页

​ 如果你也在用 MyBatis,建议尝试该分页插件,这一定是最方便使用的分页插件。分页插件支持任何复杂的单表、多表分页。

官方文档:https://pagehelper.github.io/docs/

步骤一:导入jar包

<!--pagehelper分页插件-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.6</version>
</dependency>

步骤二:在 MyBatis 配置 xml 中配置拦截器插件

<!--PageHelper分页插件-->
<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
        <property name="param" value="value"/>
    </plugin>
</plugins>

步骤三:在 Spring 配置文件中配置拦截器插件

<!--分页拦截器插件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 注意其他配置 -->
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    <!--使用下面的方式配置参数,一行配置一个 -->
                    <value>
                        <!--params=value1-->
                    </value>
                </property>
            </bean>
        </array>
    </property>
</bean>

params:为了支持startPage(Object params)方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值, 默认值为pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero

PageHelper官方使用案例

【例一】

//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
//紧跟着的第一个select方法会被分页
List<User> list = userMapper.selectIf(1);
assertEquals(2, list.get(0).getId());
assertEquals(10, list.size());
//分页时,实际返回的结果list类型是Page<E>,如果想取出分页信息,需要强制转换为Page<E>
assertEquals(182, ((Page) list).getTotal());

【例二】

//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
List<User> list = userMapper.selectAll();
//用PageInfo对结果进行包装
PageInfo page = new PageInfo(list);
//测试PageInfo全部属性
//PageInfo包含了非常全面的分页属性
assertEquals(1, page.getPageNum());
assertEquals(10, page.getPageSize());
assertEquals(1, page.getStartRow());
assertEquals(10, page.getEndRow());
assertEquals(183, page.getTotal());
assertEquals(19, page.getPages());
assertEquals(1, page.getFirstPage());
assertEquals(8, page.getLastPage());
assertEquals(true, page.isFirstPage());
assertEquals(false, page.isLastPage());
assertEquals(false, page.isHasPreviousPage());
assertEquals(true, page.isHasNextPage());

PageHelper实现分页小案例

【示例 】Mapper.java

@Repository
public interface ArticleMapper {
    List<Article> getArticleListByLike(@Param("keywords") String keywords);
}

【示例 】Mapper.xml

<mapper namespace="com.singerw.dao.ArticleMapper">
    <select id="getArticleListByLike" resultMap="artilceMap">
    SELECT g_article.article_id,
        g_article.article_title,
        g_article.article_content,
        g_article.acticle_img,
        g_article.acticle_author,
        g_article.acticle_type,
        g_article.acticle_visits,
        g_article.acticle_time,
        g_article.acticle_status,
        g_acticletype.a_id,
        g_acticletype.a_type,
        g_acticletype.act_type
    FROM g_article 
    INNER JOIN 
         g_acticletype
    ON
         g_article.acticle_type = g_acticletype.act_type
    WHERE 
         g_article.article_title LIKE #{keywords}
</select>

    <resultMap id="artilceMap" type="article">
    <id property="artID" column="article_id"/>
    <result property="artTitle" column="article_title"/>
    <result property="artContent" column="article_content"/>
    <result property="artImg" column="acticle_img"/>
    <result property="artAuthor" column="acticle_author"/>
    <result property="artVisits" column="acticle_visits"/>
    <result property="artCreateTime" column="acticle_time"/>
    <result property="artStatus" column="acticle_status"/>

    <association property="articleType" column="acticle_type">
    <id property="typeID" column="a_id"/>
    <result property="typeTitle" column="a_type"/>
    <result property="typeNumber" column="act_type"/>
    </association>
    </resultMap>
    </mapper>

【示例 】Service.java

public interface ArticleService {
    ResponseData<Article> getArticleListByLike(String keywords,int page,int pageSize);
}

【示例 】ServiceImpl.java

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public ResponseData<Article> getArticleListByLike(String keywords,int page,int pageSize) {
        if (keywords != null) {
            keywords = "%" + keywords + "%";
        }
        PageHelper.startPage(page,pageSize);
        List<Article> articleList = articleMapper.getArticleListByLike(keywords);
        PageInfo pageInfo = new PageInfo(articleList);
        ResponseData<Article> responseData = new ResponseData<Article>(0, "查询成功", pageInfo.getTotal(), articleList);
        return responseData;
    }
}

【示例 】Controller.java

@RestController
@RequestMapping("/api")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/artAll")
    public ResponseData<Article> getArticleList1(
        @RequestParam(name = "page", required = true, defaultValue = "0") int page,
        @RequestParam(name = "limit", required = true, defaultValue = "10") int limit,
        @RequestParam(name = "keywords", required = true, defaultValue = "") String keywords) {
        ResponseData<Article> articleList = articleService.getArticleListByLike(keywords, page, limit);
        return articleList;
    }
}
最后修改:2021 年 08 月 31 日 11 : 10 AM
如果觉得我的文章对你有用,请随意赞赏