Mybatis 数据库物理分页 PageHelper的使用教程

以前使用ibatis/mybatis,都是比人配置好的我们只需要用就好了,最近一个人在做一个小项目,需要用到就去网上看了一下教程,发现还挺简单的,PageHelper感觉还不错是通过mybatis的pulgin来实现Interceptor接口

下面开始吧

1. Maven项目引入依赖Jar包,

<!--  Mybatis数据库物理分页 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.4</version>
</dependency>

2. 配置分页拦截器

PageHelper的原理是基于拦截器实现的。拦截器的配置有两种方法,一种是在mybatis的配置文件中配置,一种是直接在spring的配置文件中进行:

我用的是在mybatis-config.xml文件中配置:

<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
        <property name="dialect" value="mysql"/>
    </plugin>
</plugins>
到这里PageHelper所需要的配置已经完成,下面还需要在service类中加入分页参数的具体代码:


3. 向拦截器传递分页参数

扫描二维码关注公众号,回复: 1581314 查看本文章
/**
 *
 * @param map  查询的条件  我是通过Map传参
 * @param page  第几页
 * @param size  每页显示的长度(条数)
 * @return
 */
public PageInfo<User> selectByUsersPageInfo(Map<String, Object> map, int page, int size) {
    PageHelper.startPage(page,size);
    //selectByUsers调用的是前面没分页的方法
    List<User> userPageInfo = userMapper.selectByUsers(map);
    return new PageInfo<User>(userPageInfo);
}
这是SelectByUsers的xml,

<select id="selectByUsers" parameterType="java.util.Map" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from user
  <where>
    <if test="id!=null and id!=''">
      AND ID = #{id}
    </if>
    <if test="keyy!=null and keyy!=''">
      AND Keyy = #{keyy}
    </if>
    <if test="name!=null and name!=''">
      AND Name = #{name}
    </if>
  </where>
</select>

我认为这种方式不入侵mapper代码。

其实一开始看到这段代码时候,我觉得应该是内存分页。其实插件对mybatis执行流程进行了增强,添加了limit以及count查询,属于物理分页


这是Controller

PageInfo<User> userPageInfo = userService.selectByUsersPageInfo(map,pageindex,leng);
map.clear();
map.put("rows",userPageInfo.getList());//这是分页好的对象集合
map.put("total",userPageInfo.getTotal()); //一共有多少条符合条件的数据
map.put("pageNum",userPageInfo.getPageNum()); //一共多少页,还有很多,需要的可以自己去试试
return  map;

参考项目 : https://github.com/pagehelper/Mybatis-PageHelper


猜你喜欢

转载自blog.csdn.net/javareact/article/details/78815421
今日推荐