Spring Boot集成Mybatis使用PageHelper分页查询

it2026-01-14  8

在web开发中经常用到分页查询,比如当某个页面查询返回的数据量较大时,为了提高性能和用户体验我们肯定不能将数据库中所有的数据一次性返回给前端,这样如果数据量大的话就会比较耗时。所以我们就需要用到分页查询,从而可以提高查询性能。 这里为什么会使用PageHelper插件。是因为PageHelper是一款开源的Mybatis第三方物理分页插件,使用起来很方便,可以自动拼接mapper.xml配置里的对应的sql语句,也就是说不用我们去写sql语句的一些配置,直接使用原来的查询所有的sql语句就行。Spring Boot项目中集成PageHelper插件也非常的简单。 一.首先引入pagehelper 的 依赖jar包

<!--分页插件 https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>

二.编写测试例子 1.mapper中写好sql语句

<resultMap id="setArticle" type="Article"> <id column="article_id" property="article_id" /> <result column="article_title" property="article_title" /> <result column="article_comtent" property="article_comtent" /> <result column="article_type" property="article_type" /> <result column="user_id" property="user_id" /> <result column="reading_quantity" property="reading_quantity" /> <result column="create_time" property="create_time" /> <result column="update_time" property="update_time" /> </resultMap> <select id="findAllArticleList" resultMap="setArticle"> SELECT * FROM Article </select>

2.dao 接口

Page<Article> findAllArticleList();

3.service 接口

Page<Article> getAllArticleList();

实现类

@Override public Page<Article> getAllArticleList() { return articleDao.findAllArticleList(); }

4.controller控制层

@RequestMapping("/getAllArticleList") public Map<String,Object> getAllArticleList(int pageNum,int pageSize){ Map<String,Object> map = new HashMap<>(); PageHelper.startPage(pageNum,pageSize); Page<Article> data = articleService.getAllArticleList(); map.put("data", data); return map; }

使用方法和常规分页方法一样,最后在浏览器请求地址,传好页码和页条数就行。是不是很简单呢?有什么不懂可以留言噢!

最新回复(0)