分页助手PageHelper学习

PageHelper是mybatis的通用分页插件,通过mybatis的拦截器实现分页功能,拦截sql查询请求,添加分页语句, 最终实现分页查询功能。
在 springboot上集成pagehelper,PageHelper的使用方法及原理如下: 在调用dao的service方法中设置分页参数:PageHelper.startPage(page, size),分页参数会设置在ThreadLocal中,PageHelper在mybatis执行sql前进行拦截,从ThreadLocal取出分页参数,修改当前执行的sql语句,添加分页 sql。 最后执行添加了分页sql的sql语句,实现分页查询。

1、 PageHelper配置 

添加依赖

<dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper‐spring‐boot‐starter</artifactId>  
   <version>1.2.4</version> </dependency>

2、配置pageHelper

在yml中写入配置

pagehelper:   
  helper‐dialect: mysql

3、测试

1)定义mapper接口

@Mapper 
public interface CourseMapper {
     CourseBase findCourseBaseById(String id);
    Page
<CourseInfo> findCourseListPage(CourseListRequest courseListRequest); }

2)定义mapper.xml映射文件

<select id="findCourseListPage" resultType="com.xuecheng.framework.domain.course.ext.CourseInfo"  parameterType="com.xuecheng.framework.domain.course.request.CourseListRequest">
    SELECT
     course_base.*,
    (SELECT pic FROM course_pic WHERE courseid = course_base.id) pic
    FROM
     course_base
</select>

3)测试dao

@Test
 public void testPageHelper(){
     PageHelper.startPage(1, 10);//查询第一页,每页显示10条记录      
     CourseListRequest courseListRequest = new CourseListRequest();     
     Page<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
     List<CourseInfo> result = courseListPage.getResult();
    System.out.println(courseListPage); }

猜你喜欢

转载自www.cnblogs.com/yamiya/p/12369944.html