Mybatis之分页插件PageHelper的使用教程
- step1 引入pagehelper插件依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
- step2 在mybatis-config.xml文件中配置插件
<plugins>
<!-- mybatis分页拦截器 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 分页参数合理化参数配置 -->
<property name="reasonable" value="true"/>
<!-- 配置helperDialect属性来指定分页插件使用哪种方言 -->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
- step3 在UserMapper接口中编写查询代码
/**
* 查询所有的User,通过分页查询插件pageHelper完成
* @return
*/
List<User> selectAll();
4.step4 在UserMapper.xml文件中编写查询代码
<select id="selectAll" resultType="User">
select <include refid="columes"></include> from user
</select>
- step5 在test类中编写测试代码
@Test
public void testSelectAll() throws Exception {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//在执行DQL语句之前一定要开启分页功能
int pageNum = 1;
int pageSize = 3;
PageHelper.startPage(pageNum,pageSize);
List<User> users = mapper.selectAll();
users.forEach(System.out::println);
sqlSession.close();
}
- step6 查询成功