首页 > 其他 > 详细

【总结】mybatis分页(实现 + 原理)

时间:2020-09-30 16:59:10      阅读:43      评论:0      收藏:0      [点我收藏+]

1.mybatis pageHelper分页实现

(1)引入依赖
(2)配置pageHelper插件

<configuration>
	<!-- 引入 pageHelper插件 -->
	<!--注意这里要写成PageInterceptor, 5.0之前的版本都是写PageHelper, 5.0之后要换成PageInterceptor-->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!--reasonable:分页合理化参数,默认值为false,直接根据参数进行查询。
			  当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。-->
			<!--<property name="reasonable" value="true"/>-->
		</plugin>
	</plugins>
</configuration>

(3)实现分页

    public void queryByPage(User userParam,Integer pageNum,Integer pageSize) {
        //利用PageHelper分页查询 注意:这个一定要放查询语句的前一行,否则无法进行分页,因为它对紧随其后第一个sql语句有效
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.queryByPage(userParam);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
    }

2.mp简单查询分页实现

如果查询结果为单表查询,例如查询用户列表,则可以调用mybatis plus的自动生成的mapper中的selectPage()或者selectMapsPage()方法,
Page类的构造函数中第一个参数为当前查询第几页,第二个参数为每页的记录数

        IPage<TemplateContent> page = this.page(new Page<>(request.getPage(), request.getPageSize()), qw);
        PageInfo<TemplateContent> pageInfo = new PageInfo<>(page.getTotal(), page.getRecords());
        return pageInfo;

this.page()内部其实就是调用的baseMapper.selectPage(page, queryWrapper)

3.mp复杂(关联)查询分页实现

这种查询一般需要写xml。若查询结果是关联多个表的操作,则需要用到自定义的mapper,此时的分页操作也很简单,只需要给mapper的第一个参数设置为Page对象即可,mybatis接口的第一个参数中,传递了Page对象,当mybatis执行此方法的时候,会被mybatis-plus的分页插件自动拦截到,并且把分页查询的结果返回到这个Page对象中

    /**
     *
     * @param page 翻页对象,可以作为 xml 参数直接使用,传递参数 Page 即自动分页
     * @return
     */
    @Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
    List<QuestionStudentVO> getQuestionStudent(Pagination page);

【总结】mybatis分页(实现 + 原理)

原文:https://www.cnblogs.com/muacheng/p/13748757.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!