Mybatis从入门到精通——分页插件pagehelper的使用(20)

一、pagehelper分页插件

pagehelper是一个开源的基于Mybatis拦截器开发的通用分页插件工具,一般项目中也是使用这个。

具体的项目地址:https://github.com/pagehelper/Mybatis-PageHelper

具体的使用说明:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

注意:该插件是中国人开发的,文档是中文的。

 

二、使用步骤:

1.引入依赖:

maven座标:

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.11</version>
    </dependency>

建议使用最新版本。

2.在Mybatis中注册该插件,并设置默认值

    <plugin interceptor="com.github.pagehelper.PageInterceptor">
      <!--  合理分页    -->
      <property name="reasonable" value="true"/>
    </plugin>

一般只设置一个reasonable(是否合理分页)为true,其它参数请参考具体文档。

3.使用代码:

public class MybatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws IOException {
        String resource = "mybatis-config.xml";
        //1.使用mybatis的工具读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.创建sqlSessionFactory
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        inputStream.close();
    }

    /**
     * 测试分页
     */
    @Test
    public void testPage() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //分页
        Page<Object> page = PageHelper.startPage(1, 2);
        //设置查询总数
        page.setCount(true);
        //设置排序字段
        page.setOrderBy("id desc");
        List<User> users = userMapper.selectList();
        System.out.println(users);
        //获取总数查询结果
        long count = page.getTotal();
        System.out.println("查询总数:"+count);
        sqlSession.close();
    }

}

说明:

1.主要通过PageHelper的startPage方法设置要查询的分页(从1开始),该方法会返回一个Page,通过设置该Page的属性可以进行分页、排序、以及总数查询.

2.只能通过设置PageHelper的startPage方法返回的Page才能使插件生效。

三、补充说明

1.该插件的使用非常简单,只需要通过静态方法设置好对应属性即可,不需要在mapper映射文件中写limit和order by,该插件会自动添加。

2.如果要查询总数,总数结果只能通过返回的Page对象获取。

3.如果存在多个mapper接口调用,则只会对第一个mapper生效,因为使用之后会马上清理。

4.该插件不适用于返回嵌套结果集的多表查询,因为Mybatis会合并其结果,导致分页数量不准确。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章