SpringBoot集成Mybatis-PageHelper分页工具类,实现3步完成分页

在Mybatis中,如果想实现分页是比较麻烦的,首先需要先查询出总的条数,然后再修改mapper.xml,为sql添加limit指令。

幸运的是现在已经不需要这么麻烦了,刘大牛实现了一个超牛的分页工具类(https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md)

到底有多牛呢?现在一个分页实现只需要2步,像下面这样:

PageHelper.startPage(pageNum, pageSize);
List<Bean> list = mapper.selectByExample(example);
return new PageInfo<>(list);

是不是跃跃欲试了?let's begin!

maven依赖

<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.1.4</version>
</dependency>
<!--pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.1</version>
</dependency>

在src/main/resources中需要创建META-INF文件夹,其中存放spring-devtools.properties文件,具体内容如下:

restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar

application.yml配置信息

#mybatis
mybatis:
#指定领域类的路径
  typeAliasesPackage: com.cky.domain
#指定mapper.xml的路径
  mapperLocations: classpath:mapper/*.xml

mapper: 
  mappers:
#此处填写需要分页的Mapper的全路径类名。例如com.cky.xxxMapper
  - xxxxx
  - xxxxx
  not-empty: false
  identity: MYSQL

pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

在Application添加@MapperScan("com.cky.mapper")指定mapper的路径

使用:

在任意的Mapper查询方法前后分别添加如下两句:需要注意的是PageHelper必须紧挨着Mapper查询方法才能使PageHelper生效,当我们把list放入PageInfo 中时,他会自动计算分页所需要的信息。

PageHelper.startPage(pageNum, pageSize);
List<Bean> list = mapper.selectByExample(example);
return new PageInfo<>(list);

本实例只讲了springboot的集成,像spring的集成可以查看上面提供的github网址,其中的教程也十分好,中文的哦!

posted @ 2018-03-06 10:39  宇的季节  阅读(1166)  评论(0编辑  收藏  举报